I recently worked on getting data binding in a .NET 2.0 application to work with a lookup combobox. The concept is pretty straight-forward (and very analogous to Delphi's TDBLookupCombobox). Databinding in .NET is pretty impressive, and a step forward from where Delphi currently is. For example, you can bind straight to business objects as opposed to being required to consume database resources/components to complete data binding. One big snag was in getting the lookup relationship to respect null values properly. For example, assume you have 2 very simple classes, Order and Supplier, that are bound via BindingSource components. Furthermore, assume you have your data binding set up properly to have a ComboBox set with DataSource=orderBindingSource, DisplayMember=Name, ValueMember=SupplierID, and nameComboBox.DataBindings.Add(new Binding("SelectedValue", this.orderBindingSource, "SupplierID", true)); (see this reference or this reference for more details). Lastly, if you populate your objects as in the example below, you will notice that the original display of the combobox is populated with the first item in the supplier list. If you scroll to the next record and then back to the first record, the combobox will display properly.
private void btnPopulate_Click(object sender, EventArgs e) { orderBindingSource.Add(new Order(1, "Test1", null)); orderBindingSource.Add(new Order(2, "Test2", 1)); supplierBindingSource.Add(new Supplier(1, "Supplier X")); supplierBindingSource.Add(new Supplier(2, "Supplier Y")); }
There are a couple of ways to fix this behavior. First, you could just reverse the order and populate the supplierBindingSource first. Alternatively, you can leave the population order alone and just call ResetBindings() after you're done populating all of the data.
private void btnPopulate_Click(object sender, EventArgs e) { orderBindingSource.Add(new Order(1, "Test1", null)); orderBindingSource.Add(new Order(2, "Test2", 1)); supplierBindingSource.Add(new Supplier(1, "Supplier X")); supplierBindingSource.Add(new Supplier(2, "Supplier Y")); orderBindingSource.ResetBindings(false); }
One other quick note. When you want to set the Order.SupplierID field to null, you cannot write code like this:
SupplierNameCombo.SelectedValue = null;
Instead, you can either set the SelectedIndex to -1, or (IMO) more elegantly, write code like this:
SupplierNameCombo.SelectedValue = DBNull.Value;
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.