I want to add some items to a combobox like this :
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
ComboboxItem item = new ComboboxItem();
item.Text = "choose a server...";
item.Value = "-1";
ComboBox_Servers.Items.Add(item);
...
and read those texts and values in SelectedIndexChanged
like this :
private void ComboBox_Servers_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(ComboBox_Servers.SelectedValue.ToString());
}
But SelectedValue is always null! what is the problem and how can I fix it?
You can take the SelectedItem
and cast it back to your class
and access its properties
.
MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);
Edit You can try using DataTextField and DataValueField, I used it with DataSource.
ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";
try this:
ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";
EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):
The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue
So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";
List<ComboboxItem> list = new List<ComboboxItem>();
ComboboxItem item = new ComboboxItem();
item.Text = "choose a server...";
item.Value = "-1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S1";
item.Value = "1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S2";
item.Value = "2";
list.Add(item);
cbx.DataSource = list; // bind combobox to a datasource
or use SelectedItem property:
if (cbx.SelectedItem != null)
Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With