Populate combobox from Datatable

Sometimes a need comes to to populate a combobox in such a way that values displayed to user are different than the actual selection options. In this case a mapping is created via code like key-value pair.
Recently I was doing the same thing, when I tried to do the same using DataTable.

Here is a code sample which shows that how to make use of DataTable to populate combobox.

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            dt.Rows.Add(1, "Batman");
            dt.Rows.Add(2, "Spiderman");
            dt.Rows.Add(2, "Iron man");
            dt.Rows.Add(2, "Megamind");
            dt.Rows.Add(2, "Bug");

            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "ID";

When you do so, combobox will show you the values specified in column "Name". But in the actual the ValueMember specified over here is column "ID".

If you check the SelectedValue property of the combobox, you will find the value from column "ID".
This technique has got many applications like showing user-friendly value to the user and use some other value for computations.

No comments:

Post a Comment