Binding List Based Controls to Data Sources

You will frequently want to expose data to the user in list-based controls. You can bind ListBox controls and ComboBox controls (but not CheckedListBox controls) to a data source by using the DataSource, DisplayMember, and ValueMember properties to bind a list-based control to a column of data in a data table.

Add a data source to your project. Adding data sources to your project is covered in detail in Chapter 5, "Configuring Connections and Connecting to Data."

► To bind a list-based control to a data source

1. In the Designer, select the list-based control that you want to bind to a data source.

2. In the Properties window, click the DataSource property to open the data source configuration interface, as shown in Figure 3-2. Set the DataSource property to a table contained in one of the data sources in your project.

H (none)

c.

El ^¡j^ CategoriesBindingSource : [3 CategoriesProducts |jJ Other Data Sources

J

(3 Add Project Data Source...

Select a BindingSource to bind to.

1—^m

l^1 Properties ^Solution ... ||j]Data So...

Figure 3-2 Setting the DataSource property

Figure 3-2 Setting the DataSource property

3. In the Properties window, click the DisplayMember property. Visual Studio displays the columns in the selected table. This is the column whose rows will be displayed in the control.

4. In the Properties window, click the ValueMember property. Choose a column name in the interface to bind the control to. This is the column whose members will provide the value that is returned from the selected index in the control.

The DataSource property indicates the data source (usually a data table) that the data in the control is drawn from. The DisplayMember property represents the column of data in the data source that is displayed to the user in the control. The ValueMember property allows you to designate an additional column of values to be represented in the control. For example, you might set the DisplayMember property to the Products column to indicate a list of products to the user but set the ValueMember to a Products-Code column that returned a numeric code for each product. In this instance, whenever an item was selected, the Selectedltem property would return the item displayed in the ListBox, and the SelectedValue property would return the corresponding item from the ProductsCode column.

Was this article helpful?

0 0

Post a comment