A common use of a ComboBox in a data bound application is as
a lookup based UI control. From a database perspective, a Lookup control is
used to provide the "lookup" values for a foreign key. For example, assume you
have a customer table with a "StateID" where the "StateID" is a foreign key
into a "States" table. From a UI perspective, you'd like to allow the user to
select a State via a ComboBox. To do this, you use Complex Binding to
bind the ComboBox to the States table (setting the ComboBox.DisplayMember and
ComboBox.ValueMember) and use Simple List Binding to bind the ComboBox
SelectedValue to the Customer "StateID".
Sample: ComboBox as a Lookup
table (VS 2005) (VS Project: ComboBoxBinding)
/* Create a new Customer (customer has "Name" */
/* and "StateID" properties) */
Customer cust = new Customer("Joe", "WA");
/* Bind the States ComboBox to the states DataTable */
/* Display the "Name" property in the ComboBox */
/* Use the "Code" property as the "Key" *
/* StatesTable contains US state information */
/* Name = full state name */
/* Code = state unique key */
this.statesCB.DisplayMember = "Name";
this.statesCB.ValueMember = "Code";
this.statesCB.DataSource = statesTable;
/* Set the default States ComboBox selected value */
/* to the Customer's StateID ("WA") */
/* This will make the ComboBox show "Washington" */
/* If the States ComboBox is changed, the Customer */
/* StateCode will be automatically updated */
this.statesCB.DataBindings.Add("SelectedValue", cust, "StateID", true);