Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

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?

like image 679
SilverLight Avatar asked Nov 30 '22 21:11

SilverLight


2 Answers

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";
like image 200
Adil Avatar answered Dec 14 '22 23:12

Adil


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());
like image 26
Arie Avatar answered Dec 14 '22 23:12

Arie