How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Article
08/02/2022
In this article
Sometimes it is useful to display data in a user-friendly format on a Windows Form, but store the data in a format that is more meaningful to your program. For example, an order form for food might display the menu items by name in a list box. However, the data table recording the order would contain the unique ID numbers representing the food. The following tables show an example of how to store and display order-form data for food.
OrderDetailsTable
OrderID
ItemID
Quantity
4085
12
1
4086
13
3
ItemTable
ID
Name
12
Potato
13
Chicken
In this scenario, one table, OrderDetailsTable, stores the actual information you are concerned with displaying and saving. But to save space, it does so in a fairly cryptic fashion. The other table, ItemTable, contains only appearance-related information about which ID number is equivalent to which food name, and nothing about the actual food orders.
The ItemTable is connected to the ComboBox, ListBox, or CheckedListBox control through three properties. The DataSource property contains the name of this table. The DisplayMember property contains the data column of that table that you want to display in the control (the food name). The ValueMember property contains the data column of that table with the stored information (the ID number).
The OrderDetailsTable is connected to the control by its bindings collection, accessed through the DataBindings property. When you add a binding object to the collection, you connect a control property to a specific data member (the column of ID numbers) in a data source (the OrderDetailsTable). When a selection is made in the control, this table is where the form input is saved.
The column of the data source table that you want to display in the control. In the previous scenario, this is "Name" (to set in code, use quotation marks).
The column of the data source table that contains the stored information. In the previous scenario, this is "ID" (to set in code, use quotation marks).
In a procedure, call the Add method of the ControlBindingsCollection class to bind the control's SelectedValue property to the table recording the form input. You can also do this in the Designer instead of in code, by accessing the control's DataBindings property in the Properties window. In the previous scenario, this is OrderDetailsTable, and the column is "ItemID".
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET Desktop feedback
feedback
.NET Desktop feedback
is an open source project. Select a link to provide feedback:
Learn how to bind the Windows Forms ComboBox and ListBox to data to perform tasks like browsing data in a database, entering new data, or editing existing data.