Alina B.
Alina B.

Reputation: 1276

Behavior of Combobox.SelectedIndexChanged

Please take a look at the code below. When the application starts the SelectedIndexChanged is called and x is of the type "Example". But when the app runs and you select something different SelectedIndexChanged produces a result x type of float. Why does this produce different results?

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var example = new List<Example>();

            example.Add(new Example("A", 100f));
            example.Add(new Example("B", 200f));
            example.Add(new Example("C", 400f));

            this.comboBox1.DataSource = example;

            this.comboBox1.DisplayMember = "Description";
            this.comboBox1.ValueMember = "Value";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var x = this.comboBox1.SelectedValue;
        }
    }

    public class Example
    {
        public Example(string desc, float val)
        {
            this.Description = desc;
            this.Value = val;
        }

        public string Description { get; set; }
        public float Value { get; set; }
    }
}

Upvotes: 1

Views: 395

Answers (1)

Alina B.
Alina B.

Reputation: 1276

Before posting my question I tried different things and found the answer:

SelectedIndexChanged is fired on setting the DataSource. At this particular moment the program is not aware which column is DisplayMember and ValueMember and returns the type Example.

To get the intended result you first have to tell the control what to use as DisplayMember and ValueMember and after that set the datasource.

this.comboBox1.DisplayMember = "Description";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = example;

Upvotes: 1

Related Questions