Datagridview and two combobox (related) - c#

i have one Datagridview and two combobox (related) When I click on dataGridView1_CellMouseClick cmbSehir.Text changes as I want. but cmbilce.Text does not change as I want!. Where do i make mistakes. I hope I made myself clear. Thanks for helping.
private void frmMusteriEkle_Load(object sender, EventArgs e)
{
GetSehir();
GetDatagridview();
}
private void GetSehir() {
db.connect();
db.SqlQuery("select * from iller");
DataTable dt = db.GeTDataTable();
DataRow dr = dt.NewRow();
dr["id"] = 0;
dr["sehir"] = "Seçiniz:";
dt.Rows.InsertAt(dr, 0);
cmbSehir.DataSource = dt;
cmbSehir.ValueMember = "id";
cmbSehir.DisplayMember = "sehir";
db.disconnect();
}
private void cmbSehir_SelectionChangeCommitted(object sender, EventArgs e)
{
if (cmbSehir.SelectedIndex != 0)
{
db.connect();
db.SqlQuery("select * from ilceler where il_id = ?");
db.command.Parameters.AddWithValue("#p", cmbSehir.SelectedValue);
DataTable dt = db.GeTDataTable();
cmbilce.DataSource = dt;
cmbilce.ValueMember = "id";
cmbilce.DisplayMember = "ilceler";
db.disconnect();
}
else
{
cmbilce.DataSource = null;
}
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
cmbSehir.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
cmbilce.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
}

Without seeing what GetDatagridview method does, I will assume from the lines…
cmbSehir.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
cmbilce.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
that these combo boxes are related to the data contained in columns 4 and 5. If the combo boxes have the same data source as the DataGridView then it is possible to bind all three controls to the same DataSource. After binding all three components to the same data source, clicking on a cell in the grid will automatically change the combo boxes and vice versa… changing a combo box will change the selection in the grid. There is no need to wire up the CellMouseClick or SelectionChanged events to keep the controls in sync.
Another consideration is the cmbSehir_SelectionChangeCommitted method that fires every time the user changes the selection in the cmbSehir combo box. In this method, the code queries the data base and sets the combo boxes data source. This is fine, however, are you sure you want to query the database and refill the combo box EVERY time the user changes this selection? I am guessing one query would be sufficient, until new data is added, removed or changed.
The code below sets the DataSource for the combo boxes to the same data source of the DataGridView using different ValueMembers.
DataTable AllData;
private void Form1_Load(object sender, EventArgs e) {
AllData = GetDT();
dataGridView1.DataSource = AllData;
comboBox1.DataSource = AllData;
comboBox2.DataSource = AllData;
comboBox1.ValueMember = "sehir";
comboBox2.ValueMember = "ilceler";
}

Related

Change FilterEditype of janus griex columns to checklistbox

i Have A Janus Gridex in Windows Form with Several Columns.
I want to Change the FilterEditType of All Columns in This GridEx to Checklistbox. So User Can Filter each Column Based on one or more than one values.
Please Give me the sample Code in C# or VB.net.
You need to add certain events for this one ,
First of all make the GridEx columns FilterEditType = Custom
Then add the Janus.Windows.GridEX.EditControls.CheckedComboBox for each column FilterEditType. For eg: add this events
private void grdTest_InitCustomEdit(object sender, Janus.Windows.GridEX.InitCustomEditEventArgs e)
{
if (e.Column.Key == "ColumnName")
{
cboTest.Visible = true;
e.EditControl = cboTest;
}
}
private void grdTest_EndCustomEdit(object sender, Janus.Windows.GridEX.EndCustomEditEventArgs e)
{
//this (dtTest) datatable is actually the datasource assigned for the grid
dtTest.DefaultView.RowFilter = string.Empty;
cboTest.Visible = false;
string Filter = string.Empty;
if (cboTest.CheckedItems != null)
{
foreach (GridEXRow row in cboTest.DropDownList.GetCheckedRows())
{
if (Filter != string.Empty)
Filter += " OR ColumnName = '";
else Filter = "( ColumnName = '";
Filter += row.Cells[2].Value;
Filter += "'";
}
Filter += " )";
}
dtTest.DefaultView.RowFilter = Filter;
grdTest.DataSource = dtTest.DefaultView;
}
private void grdTest_ClearFilterButtonClick(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
{
if (e.Column.Key == "ColumnName")
cboTest.CheckAll();
grdTest_EndCustomEdit(null, null);
}
Then for the checked combo you need to design with multiple columns as you need, but one column should be a CheckBox and make it ActAsSelector = True,
The above example the checked combo has actually 3 columns , first one checkbox , second one is an ID (primary key ) and the last one is the name. I used the name column to filter the datatable.
In the DropDown event of the combo assign the datasource for it from the GirdEx datasource:
private void cboTest_DropDown(object sender, EventArgs e)
{
int C = 1;
DataRow DR;
DataTable dtComboDS= new DataTable();
dtComboDS.Columns.Add("ID", typeof(int));
dtComboDS.Columns.Add("Name", typeof(string));
var depts = (from x in dtTest.AsEnumerable() select x.Field<string>("ColumnName")).ToList();// dtTest is actually the datasource assigned for the GridEx
foreach (var Row in depts.Distinct().ToList())
{
DR = dtComboDS.NewRow();
DR["ID"] = C++;
DR["Name"] = Row;
dtComboDS.Rows.Add(DR);
}
cboTest.DropDownDataSource = dtComboDS;
}
private void cboTest_CloseUp(object sender, EventArgs e)
{
cboTest.Visible = false;
grdTest.UpdateData();
}
On the closeup event hide the checked combo and update the grid to get the result.
Hope this will help !
Good Luck.

For a Windows Forms Application using `DataGridView`, how can I check a value in my DataSource and change the color of a separate cell?

Very specific question, I know. I'm not sure how best to word this. Currently, my cell_formatting method will change the color of a cell based on its value:
dataGridView.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.cell_formatting);
....
public void cell_formatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name.Equals("LocCode"))
{
if (e.Value.ToString() == "OK")
{
e.CellStyle.BackColor = Color.Red;
}
}
}
What I actually need to do is check a different column index than that of the one I'm changing the color of. There's a column color that will decide what color the LocCode cell will change to.
I imagine there's a way to catch which item in my dataGridView.DataSource is being looked at while inside cell_formatting(), but I don't know how to access it.
I suggest you to use DataTable to get the color value. Here is an simple example for you.
I made a Table and add 3 records in it.
In form_load, data loaded to DataGridView,
DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=serverName;Database=db;Trusted_Connection=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from TestTable", conn);
dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
Then, here we came cell_formatting event,
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("TestName")) // LocCode
{
if (e.Value != null && e.Value.ToString() != "") // Check for extra line
{
string a = dt.Rows[e.RowIndex]["Color"].ToString(); //current row's Color column value.
e.CellStyle.BackColor = Color.FromName(a); // color as backcolor
}
}
}
Output;
Hope helps,
I imagine there's a way to catch which item in my dataGridView.DataSource is being looked at while inside cell_formatting(), but I don't know how to access it.
Sure there is.
First, use the DataGridViewCellFormattingEventArgs.RowIndex property to get the index of the row being formatted. Then use the index to the get the corresponding DataRow object, and finally use the DataGridViewRow.DataBoundItem property to get the corresponding data source object, casting it to the appropriate type:
var item = dataGridView.Rows[e.RowIndex].DataBoundItem as YourDataSourceObjectType;

cant load two combo boxes with different datasources using c#?

I am loading two combo boxes with two different datasources from sql using a datatable and i'm loading it when the form loads but i dont know the reason only one combo box is filled (one at the top always fills the other one doesn't) and i have checked the datatables they are working fine
private void Form1_Load(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
customer cc1 = new customer();
comboBox2.DataSource = cc1.getplatenumber();
comboBox2.ValueMember = "Platenumber";
comboBox2.DisplayMember = "Platenumber";
comboBox2.Items.Add("Platenumber");
}
if (comboBox1.Text == "")
{
customer cc = new customer();
DataTable dt = cc.getitems();
comboBox1.DataSource = dt;
comboBox1.ValueMember = "Item_no";
comboBox1.DisplayMember = "Itemname";
comboBox1.Items.Add("Itemname");
comboBox1.SelectedIndex = 0;
}
}
any help ?
Step through the code
Ensure that the code inside the 2nd if block runs, as Rohit suggests
Verify that dt is filled as you expect
Check the strings you're using to extract data - are "Item_no" and "Itemname" correct?

Add new empty row to dataGridView bound to DataSet

I am not handy at this. I have a dataGridView bound to SQL by a dataset. All column are generated by the dataset except one column which is replaced by a coded one which is a comboboxColumn.
To avoid new columns being generated while editing a row, I have set the allowUserToAddRows to false. Now I would like to add new empty rows by button click. I have tried in several way without any success.
Updated with full code
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.affitto_saTableAdapter.Fill(this.affitto_SADataSet.affitto_sa);
DataGridViewComboBoxColumn comboCol1 = new DataGridViewComboBoxColumn();
comboCol1.Name = "Periodo Rif.";
List<DateTime> periods = new List<DateTime>() { DateTime.Now.AddMonths(-2), DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2) };
//Dates = Dates.OrderBy(x => x).ToList();
List<string> colSource = periods.Select(x => x.ToString("MMM/yyyy")).ToList();
comboCol1.DataSource = colSource;
dataGridView1.Columns.Add(comboCol1);
comboCol1.DataPropertyName = "Periodo";
dataGridView1.Columns["Periodo Rif."].DisplayIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
/* DataTable dt = dataGridView1.DataSource as DataTable;
DataRow row = dt.NewRow();
dt.Rows.Add(row);*/
(dataGridView1.DataSource as DataTable).Rows.Add((dataGridView1.DataSource as DataTable).NewRow());
}
}
How can I add a new empty row to such DGV?
Here solution for your problem:
dataGridView1.Rows.AddCopy(myDataGridView1.Rows.Count - 1);
Since your DGV not binded with any of dataSource hence AddCopy of DataGridViewRow will add new row at end of DGV (at Rows.Count - 1).
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Rows.Add();
}

Datagrid Binding Question

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Categories