Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How can I add a "null" or "DBNull" entry to my bound ComboBox?

When data bound, the Windows Forms ComboBox does not provide a general way to add a "null" or "not selected" value to its items list.  The only generally supported way to do this is to add a "null" item to your data source list.  Building on the previous states example, this would require an additional "null" row to be manually added to the States table.

Sample: Adding a "null" value to a Lookup based ComboBox (VS 2005) (VS Project: ComboBoxBinding)

/* Create a new Customer                          */
Customer cust = new Customer("Joe", null);

/* Add null value                                       */
DataRow row = statesTable.NewRow();

/* Enter a null row (ComboBox will show blank)          */
row["Name"] = "";
row["Code"] = DBNull.Value;

/* Add the row to DataTable                             */
statesTable.Rows.Add(row);

/* Bind the States ComboBox to the states DataTable     */
this.statesCB.DisplayMember = "Name";
this.statesCB.ValueMember = "Code";
this.statesCB.DataSource = statesTable;

/* Bind the ComboBox SelectedValue to the customer      */
/* business object                                      */
this.statesCB.DataBindings.Add("SelectedValue", cust, "StateID", true);