fbk2000
asked on
How do I separate Combobox values from display at design time.
Using c# 2.0, vs2005 Is there a way to separate a Combobox's display value from its data value at design time without using a database? Or perhaps a way to make it have two columns? I need to store a key value and display a different value like html select list. I have a small amount of values (10) that I need to just input at design time. It needs to be light weight.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
U can also use DataTable
Here is ur final code:
DataTable dt = new DataTable("data");
dt.Columns.Add("key");
dt.Columns.Add("value");
dt.Rows.Add(new object[] { "key1", "value1" });
dt.Rows.Add(new object[] { "key2", "value2" });
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "key";
comboBox1.ValueMember = "value";
private void comboBox1_SelectedIndexCha nged(objec t sender, EventArgs e)
{
MessageBox.Show(comboBox1. SelectedVa lue.ToStri ng());
}
In combobox it displays "key1,key2"
In the event for value u will get "value1,value2"
DataTable dt = new DataTable("data");
dt.Columns.Add("key");
dt.Columns.Add("value");
dt.Rows.Add(new object[] { "key1", "value1" });
dt.Rows.Add(new object[] { "key2", "value2" });
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "key";
comboBox1.ValueMember = "value";
private void comboBox1_SelectedIndexCha
{
MessageBox.Show(comboBox1.
}
In combobox it displays "key1,key2"
In the event for value u will get "value1,value2"
hi, if you want to attach the key/value pairs to the combobox at design time both the approaches suggested by udhayakumard are good. as you also say that the no. of items in the combobox wont be more than 10, i will strongly recommend using the hashtable approach as it will be more efficient than the datatable approach.
Hashtable hLang = new Hashtable();
hLang.Add("1", "ASP.NET");
hLang.Add("2", "C#");
hLang.Add("3", "VBNET");
cbo1.DataSource = hLang;
cbo1.DataBind();