Windows Forms: ListBox and ComboBox
Demonstrates binding ListBox and ComboBox controls, and working with selected
items.
Highlights
Demonstrates several different techniques for binding data to ListBox and
ComboBox controls, and shows different ways to retrieve the selected item or
items from the controls.
Requirements
This application requires the release version of Visual Studio .NET Professional
(or greater) and access to the Northwind database residing in SQL Server or the
Microsoft Data Engine (MSDE). To install MSDE, do the following:
1. Open the Start menu, click Programs, click Microsoft .NET
Framework SDK, and then click Samples and Quickstart Tutorials.
2. Click "Step 1: Install the .NET Framework Samples Database".
3. Open a command window, and CD to
\Samples\Setup This is typically : C:\Program Files\Microsoft
Visual Studio .NET\FrameworkSDK\Samples\Setup
4. Type: osql -E -S (local)\NetSDK -i InstNwnd.sql
Running the Sample
The pages of the Tab control on the sample demonstrate different techniques:
-
Add Items: Demonstrates how to add objects to a ListBox
control, using the DisplayMember property of the control to determine which
property of the objects contained within the list displays in the list. (Note
that because this example doesn't set the DataSource property of the control,
and instead adds items individually, the code can't use the ValueMember
property of the control to retrieve the selected value when you select
something. See the lstProcessesAddItem_SelectedIndexChanged procedure for more
details.)
-
Selection Mode: Allows you to test out different styles of
multi-select list boxes. Selecting items displays the SelectedIndices
collection and the SelectedItems collection. (To see list box controls with the
SelectionMode set to Nothing, check out the two controls displaying selected
items on the page.)
-
Bind to DataTable: Fills a DataTable with a list of all
files in your C:\ folder, then binds the list box to that DataTable.
-
Bind to Array: Binds a list box to the results of
retrieving all running processes—an array of Process objects. Demonstrates the
use of the DisplayMember and ValueMember properties.
-
ComboBox: Demonstrates binding to a DataTable retrieved from
SQL Server. This example expects that it can find the Northwind
sample database in SQL Server on the local computer. The page also allows you
to try out some of the layout properties that affect the behavior of the combo
box.