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


.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml