How to Bind a C Sharp Collection to a List Box
It only takes a simple "Add" command to add items to a C Sharp ListBox. ListBoxes, when displayed on forms, display useful information to an application's user. Another way to populate a C Sharp ListBox is to bind it to a collection. A collection is an object such as a generic "List" that contains related items. For example, a List collection populated with car names might be important to display on a form. Bind the collection to a C Sharp ListBox using a single command.
Instructions
-
-
1
Open one of your C Sharp projects using Visual Studio. Find your project's startup form icon in the Solution Explorer and double-click that icon. The form opens in the Design window and displays its controls.
-
2
Click "View" and select "Toolbox" to display the Toolbox window. Double-click the "ListBox" item in the Toolbox window to place a ToolBox control on the form. The ToolBox's name is "listBox1."
-
-
3
Double-click the form's title bar to display the Code window. Visual Studio positions your cursor inside the form's "Load" method. This method runs when the application runs.
-
4
Paste the following code into this method:
List<string> carCollection = new List<string>();
carCollection.Add("Ford");
carCollection.Add("Honda");
carCollection.Add("Pontiac");listBox1.DataSource = carCollection;
The first four lines of code create a new collection that contains car names. The final line binds the ListBox to the collection by setting its DataSource property to the name of the collection.
-
5
Press "F5" to run the project and display the form. The "Load" method runs and binds the ListBox to the collection. The car names appear inside the ListBox.
-
1
Tips & Warnings
If your application has multiple collections, you can bind any of them to a ListBox at any time by setting the ListBox's DataSource property to the name of the desired collection. To clear the items from a ListBox, set its DataSource property to null.