Programmatically Binding DataSource To ComboBox In Multiple Ways

Sometimes we need to load a list of items to a ComboBox or DropDownList for the user to select a value to be processed. Items are loaded in the ComboBox generally to be bound to a data source of the ComboBox. A The data source is bound to a ComboBox using the "DataSource" property.

As per MSDN documentation, DataSource can be an object that implements the IList interface (such as a DataSet, DataTable, List, Array, and DataView). The default is null. When the DataSource property is set, the items collection cannot be modified.

To explain data source binding with various objects I created a demo project that demonstrates the following kind of bindings:

  • Binding DataSource with Array
  • Binding DataSource with List
  • Binding DataSource with DataSet
  • Binding DataSource with DataTable
  • Binding DataSource with DataView
  • Binding DataSource with Enumeration Values

For our understanding a sample project is also attached with this article. Here is a screen shot of the main form of the project:

image1.jpg

Binding with Array

We know that any object implementing the IList interface can be bound to a "ComboBox.DataSource". Array is one of them. Suppose we have a class "Person" with the properties: Name, Rank and Gender. Now we want to populate a ComboBox with the person's name and when the user selects a name on the list, his/her corresponding gender is displayed. Here is the related code

  1. class Person {  
  2.     public string Name {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public int Rank {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string Gender {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public Person(int r, string n, string g) {  
  15.         Rank = r;  
  16.         Name = n;  
  17.         Gender = g;  
  18.     }  
  19. }  
  20. private void btn_FillWithArray_Click(object sender, EventArgs e) {  
  21.     try {  
  22.         Person[] list = new Person[] {  
  23.             new Person(1, "Jon""M"),  
  24.                 new Person(2, "Ram""M"),  
  25.                 new Person(3, "Rin""F"),  
  26.                 new Person(4, "Sue""F"),  
  27.                 new Person(5, "Ken""M"),  
  28.                 new Person(6, "Tom""M"),  
  29.                 new Person(7, "Sam""M")  
  30.         };  
  31.         comBox_FilledWithArray.DataSource = list;  
  32.         comBox_FilledWithArray.DisplayMember = "Name";  
  33.         comBox_FilledWithArray.ValueMember = "Gender";  
  34.     } catch (Exception exc) {  
  35.         MessageBox.Show(exc.Message);  
  36.     }  
  37. }  
  38. private void comBox_FilledWithArray_SelectionChangeCommitted(object sender, EventArgs e) {  
  39.     lbl_ArrayValue.Text = "Gender: " + comBox_FilledWithArray.SelectedValue.ToString();  
  40. }  
image2.jpg

Binding with List

A List collection in .Net also implements the IList interface so it can be bound to a ComboBox's DataSource too. Here we want to display a person's rank in the list and when the user selects a rank from the ComboBox items, the corresponding name is displayed.
  1. private void btn_FillWithList_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         List < Person > list = new List < Person > () {  
  4.             new Person(1, "Jon""M"),  
  5.                 new Person(2, "Ram""M"),  
  6.                 new Person(3, "Rin""F"),  
  7.                 new Person(4, "Sue""F"),  
  8.                 new Person(5, "Ken""M"),  
  9.                 new Person(6, "Tom""M"),  
  10.                 new Person(7, "Sam""M")  
  11.         };  
  12.         comBox_FilledWithList.DataSource = list;  
  13.         comBox_FilledWithList.DisplayMember = "Rank";  
  14.         comBox_FilledWithList.ValueMember = "Name";  
  15.     } catch (Exception exc) {  
  16.         MessageBox.Show(exc.Message);  
  17.     }  
  18. }  
  19. private void comBox_FilledWithList_SelectionChangeCommitted(object sender, EventArgs e) {  
  20.     lbl_ListValue.Text = "Name: " + comBox_FilledWithList.SelectedValue.ToString();  
  21. }  
image3.jpg

Binding with DataSet


Since DataSet implements the IList interface too, it can be bound to a ComboBox's DataSource. Now let us see how to bind a DataSet as a Data Source. Assume you get the data from a database into a DataSet using a Stored Procedure "usp_GetAllAddresses" (refer to the "GetDataFromDatabaseinDataSet()" method and the following Stored Procedure). Here we can see that the columns names are ID, LastName, FirstName and City. Out of these columns any two columns that can be chosen as DispalyMember and as ValueMember respectively while binding with DataSet.

STORED PROCEDURE
  1. CREATE PROCEDURE [dbo].[usp_GetAllAddresses]   
  2. AS  
  3. BEGIN  
  4. SELECT [P_Id] as ID  
  5. ,[LastName] as LastName  
  6. ,[FirstName] as FirstName  
  7. ,[Address] as Address  
  8. ,[City] as City  
  9. FROM [ADDRESS]  
  10. END  
CODE
  1. private void btn_FillWithDataSet_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         DataSet dsDataFromDB = GetDataFromDatabaseinDataSet();  
  4.         comBox_FilledWithDataSet.DataSource = dsDataFromDB.Tables[0];  
  5.         comBox_FilledWithDataSet.DisplayMember = "FirstName";  
  6.         comBox_FilledWithDataSet.ValueMember = "City";  
  7.     } catch (Exception exc) {  
  8.         MessageBox.Show(exc.Message);  
  9.     }  
  10. }  
  11. private void comBox_FilledWithDataSet_SelectionChangeCommitted(object sender, EventArgs e) {  
  12.     lbl_DataSetValue.Text = "City Name: " + comBox_FilledWithDataSet.SelectedValue.ToString();  
  13. }  
  14. public DataSet GetDataFromDatabaseinDataSet() {  
  15.     DataSet ds = new DataSet();  
  16.     try {  
  17.         // database Connection String  
  18.         string connectionString = "Server = .; database = HKS; Integrated Security = true";  
  19.         using(SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString)) {  
  20.             using(SqlDataAdapter SqlDa = new SqlDataAdapter("usp_GetAllAddresses", sqlCon)) {  
  21.                 SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;  
  22.                 SqlDa.Fill(ds);  
  23.             }  
  24.         }  
  25.         return ds;  
  26.     } catch (Exception) {  
  27.         throw;  
  28.     }  
  29. }  
image4.jpg

Binding with DataTable

Here we are getting data from a database in a DataTable instead of a DataSet (as in the previous section) and bind it to a Combo Box.
  1. private void btn_FillWithDataTable_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         DataTable dtDataFromDB = GetDataFromDatabaseinDataTable();  
  4.         comBox_FilledWithDataTable.DataSource = dtDataFromDB;  
  5.         comBox_FilledWithDataTable.DisplayMember = "ID";  
  6.         comBox_FilledWithDataTable.ValueMember = "FirstName";  
  7.     } catch (Exception exc) {  
  8.         MessageBox.Show(exc.Message);  
  9.     }  
  10. }  
  11. private void comBox_FilledWithDataTable_SelectionChangeCommitted(object sender, EventArgs e) {  
  12.     lbl_DataTableValue.Text = "First Name: " + comBox_FilledWithDataTable.SelectedValue.ToString();  
  13. }  
  14. public DataTable GetDataFromDatabaseinDataTable() {  
  15.     DataTable dt = new DataTable();  
  16.     try {  
  17.         // database Connection String  
  18.         string connectionString = "Server = .; database = HKS; Integrated Security = true";  
  19.         using(SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString)) {  
  20.             using(SqlDataAdapter SqlDa = new SqlDataAdapter("usp_GetAllAddresses", sqlCon)) {  
  21.                 SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;  
  22.                 SqlDa.Fill(dt);  
  23.             }  
  24.         }  
  25.         return dt;  
  26.     } catch (Exception) {  
  27.         throw;  
  28.     }  
  29. }  
image5.jpg

Binding with DataView

DataView in .Net also implements the IList interface, so it can be bound to a ComboBox's DataSource too. DataView is generally used to get a collection in a desired view after filtering out some rows from a DataTable. In the following code, we got the data from the database in a DataTable and after that we filtered out some rows ( ID > 5 ) and saved the required filtered data into a DataView.
  1. private void btn_FillWithDataView_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         DataTable dtDataFromDB = GetDataFromDatabaseinDataTable();  
  4.         // Filtering rows with DataView class  
  5.         DataView dv = new DataView(dtDataFromDB);  
  6.         dv.RowFilter = "ID < 5";  
  7.         comBox_FilledWithDataView.DataSource = dv;  
  8.         comBox_FilledWithDataView.DisplayMember = "ID";  
  9.         comBox_FilledWithDataView.ValueMember = "FirstName";  
  10.     } catch (Exception exc) {  
  11.         MessageBox.Show(exc.Message);  
  12.     }  
  13. }  
  14. private void comBox_FilledWithDataView_SelectionChangeCommitted(object sender, EventArgs e) {  
  15.     lbl_DataViewValue.Text = "First Name: " + comBox_FilledWithDataView.SelectedValue.ToString();  
  16. }  
image6.jpg

Binding with Enumeration


We could bind any ComboBox to a list of an enumeration values easily by using its GetValues() method. Actually the GetValues() method of Enum returns an array of objects (as we know, that implements the IList interface). We can use this method to convert an enum to an array and bind to a ComboBox.
  1. enum Weekdays {  
  2.     Sunday,  
  3.     Monday,  
  4.     Tuesday,  
  5.     Wednesday,  
  6.     Thursday,  
  7.     Friday,  
  8.     Saturday,  
  9. };  
  10. private void btn_FillWithEnumeration_Click(object sender, EventArgs e) {  
  11.     comBox_FilledWithEnumeration.DataSource = Enum.GetValues(typeof(Weekdays));  
  12. }  
  13. private void comBox_FilledWithEnumeration_SelectionChangeCommitted(object sender, EventArgs e) {  
  14.     lbl_EnumerationValue.Text = "Selected day is: " + comBox_FilledWithEnumeration.SelectedValue.ToString();  
  15. }  
image7.jpg

Summary

So here we learned how to bind a ComboBox DataSource to any Array of objects, List of Objects, DataTable, DataSet, DataView and Enumeration Values.

 

Up Next
    Ebook Download
    View all
    Learn
    View all