Hello all,
I am new to C# and thought I would post here based upon a posting I saw here yesterday indicating it is a good forum for beginners. Have been posting on CP, but I think I am just annoying them there......:icon_sad:
Anyway, I have been struggling with a DataGridView with two comboBox columns. I trying to filter the second column based upon the selection of the first column. Please see the code below:
You'll notice I have a comment in primaryCB_SelectedIndexChanged regarding wanting to set the bindingSource for the second ComboBox. However, I have tried a multitude of things without success. This seems like a straightforward problem, but I am finding otherwise (at least for someone with my skills). Thanks.
public void Form1_Load(object sender, EventArgs e)
{
DataTable tblPrimary = dataSet1.Tables.Add("Primary");
tblPrimary.Columns.Add("Type");
tblPrimary.Rows.Add("Force");
tblPrimary.Rows.Add("Torque");
tblPrimary.Rows.Add("Pressure");
DataTable tblSecondary = dataSet1.Tables.Add("Secondary");
tblSecondary.Columns.Add("Primary_Type"); tblSecondary.Columns.Add("Unit");
tblSecondary.Rows.Add("Force", "lb");
tblSecondary.Rows.Add("Force", "N");
tblSecondary.Rows.Add("Force", "oz");
tblSecondary.Rows.Add("Torque", "in-lb");
tblSecondary.Rows.Add("Torque", "oz-in");
tblSecondary.Rows.Add("Torque", "N-m");
dataGridView1.DataSource = tblSecondary;
DataGridViewComboBoxColumn clmType = new DataGridViewComboBoxColumn();
clmType.DataSource = tblPrimary;
clmType.ValueMember = "Type";
dataGridView1.Columns.Add(clmType);
DataGridViewComboBoxColumn clmUnit = new DataGridViewComboBoxColumn();
clmUnit.DataSource = tblSecondary;
clmUnit.ValueMember = "Unit";
dataGridView1.Columns.Add(clmUnit);
}//end of Form1_Load
private void primaryCB_SelectedIndexChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0) //allow control on only one column
{
ComboBox cb = sender as ComboBox;
if (cb != null)
{
Debug.WriteLine(cb.SelectedValue + "TEST");
BindingSource bsSecondary = new BindingSource();
bsSecondary.DataSource = dataSet1.Tables["tblSecondary"];
string filter = string.Format("Primary_Type = {0}", cb.SelectedValue);
bsSecondary.Filter = filter;
Debug.WriteLine(filter);
//I want to have something like
//clmUnit.DataSource = bsSecondary;
//here, but that doesn't work....
}
}
}//end of primaryCB_SelectedIndexChanged
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0) //allow control only on one column
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
//need to remove the handler first, otherwise will occur for each row in grid as new row is added
cb.SelectedIndexChanged -= primaryCB_SelectedIndexChanged;
cb.SelectedIndexChanged += primaryCB_SelectedIndexChanged;
}
}
}// End of EditingControlShowing