Reputation: 115
I would like to store two items per item e.g. Name and description. in the combobox the selected item will show the Name and a label will show the description for the item, whenever the selected item is changed the label needs to update.
What I have below seems to store the items but not display them based on the selected index or whenever the item selection is changed!
ComboboxItem item = new ComboboxItem();
item.Text = "A1";
item.Value = "A2";
comboBox1.Items.Add(item);
item.Text = "B1";
item.Value = "B2";
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
label1.Text = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
}
And a Class with:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Upvotes: 1
Views: 941
Reputation: 19189
ComboBoxItem
is reference type. You have to create new item before adding it to comboBox1
items Otherwise it will also change the previous added items.
Change this part
ComboboxItem item = new ComboboxItem();
item.Text = "A1";
item.Value = "A2";
comboBox1.Items.Add(item);
// Will change value of item thus item added to combo box will change too because the references are same
item.Text = "B1";
item.Value = "B2";
comboBox1.Items.Add(item);
To this
ComboboxItem item = new ComboboxItem();
item.Text = "A1";
item.Value = "A2";
comboBox1.Items.Add(item);
ComboboxItem item2 = new ComboboxItem();
item2.Text = "B1";
item2.Value = "B2";
comboBox1.Items.Add(item2);
Upvotes: 2