Are the valuesfor the ComboBox from database? If so, I think you may havea table for binding the controls on the form, and another table for binding the ComboBox,see example below. (To make things easy I just create DataTable objects by code, however, you can load data from database, the logic for binding is the same)
Code Block
void Form1_Load(object sender, EventArgs e)
//dt1 for binding the controls on form
DataTable dt1 = new DataTable();
"c1");
"sid");
"aaa", 3);
"bbb", 2);
"ccc", 1);
"ddd", 4);
//dt2 for binding the ComboBox
DataTable dt2 = new DataTable();
"id",typeof(int));
"species");
"man");
"fish");
"bird");
"mamal");
//bind the ComboBox
this.comboBox1.DisplayMember = "species";
this.comboBox1.ValueMember = "id";
this.comboBox1.DataSource = dt2;
//bind controls on the form
this.textBox1.DataBindings.Add("Text", dt1, "c1", true,
DataSourceUpdateMode.OnPropertyChanged);
this.comboBox1.DataBindings.Add("SelectedValue", dt1, "sid",true,
DataSourceUpdateMode.OnPropertyChanged);
If the values for the ComboBox are not from database, i.e. you they're added manually, then you can do something like this
Code Block
void Form1_Load(object sender, EventArgs e)
//dt1 for binding the controls on form
DataTable dt1 = new DataTable();
"c1");
"species");
"aaa", "bird");
"bbb", "fish");
"ccc", "man");
"ddd", "mamal");
//populate the ComboBox
this.comboBox1.Items.Add("man");
this.comboBox1.Items.Add("fish");
this.comboBox1.Items.Add("bird");
this.comboBox1.Items.Add("mamal");
//bind controls on the form
this.textBox1.DataBindings.Add("Text", dt1, "c1", true,
DataSourceUpdateMode.OnPropertyChanged);
this.comboBox1.DataBindings.Add("SelectedItem", dt1, "species",true,
DataSourceUpdateMode.OnPropertyChanged);
You can filter the BindingSource by setting the Filter property, something like this
Code Block
privatevoid Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name");
for (int j = 0; j < 10; j++)
{
dt.Rows.Add(j, "row" + j.ToString());
}
BindingSource bs = new BindingSource();
bs.DataSource = dt;
bs.Filter = "id<5";
this.comboBox1.DisplayMember = "name";
this.comboBox1.ValueMember = "id";
this.comboBox1.DataSource = bs;
}
|