Search code examples
c#windowscomboboxgeneric-listselectedvalue

Windows ComboBox Selected Item (populated from List<>)


I am setting a combobox item like this:

List<Object> items = new List<Object>();
items.Add(new { Text = "MyVal", Value = 1 });
cbo.DataSource = items;

It then in VS returns:

enter image description here

But I cannot simply now say cbo.SelectedItem.Text or cbo.SelectedItem.Value. If i try this, I get the error

"object does not contain a definition for value and no extension method value 
accepting a first argument of type object could be found"

How can I get the Value Property please

Based on great replies, I have now added this, to show that I cannot get the properties of Text or Value at all. enter image description here

I've tried this code to pass the "string" into

 public class ComboboxItem
    {
        public string Text { get; set; }
        public short Value { get; set; }

        public ComboboxItem(string t, short v)
        {
            Text = t;
            Value = v;
        }

    }

Solution

  • The combo box is bound to a list containing anonymous types. You ought to use the dynamic keyword.

    dynamic item = cbo.SelectedItem;
    
    String text = item.Text;
    Int32 value = item.Value;