I am trying to learn some basic data manipulation through Entity Framework. In this particular scenario, I happen to stumble upon some ambiguous lines of code I found online.
I have a Combobox, with DisplayMember property and ValueMember Property Set to particular column names of a table somewhere. My interpretation, until now, was to bind DisplayMember and ValueMember after I have set the DataSource property of Combobox as it feels more intuitive. Like this:
ComboBox1.DataSource = SalesEntity.Products.ToList();
ComboBox1.DisplayMember = "CategoryName"
ComboBox1.ValueMember = "CategoryId"
In a program that I am currently working on, I got a CastException, working with this approach. I knew it was indeed a RuntimeError, but I couldn't see my Form(the process had started, but yet not shown)! I figured out that the SelectedIndexChanged event triggers as soon as the form loads. So after a few google clicks, I came by this thread:
ComboBox.ValueMember and DisplayMember
It explained that the DataSource should be set after binding the DisplayMember and ValueMember properties with the column, in order to avoid these errors.
ComboBox1.DisplayMember = "CategoryName"
ComboBox1.ValueMember = "CategoryId"
ComboBox1.DataSource = SalesEntity.Products.ToList();
Although it worked I want to know why does this work?
My thoughts: I assume that setting the ComboBox to dataSource at first, initializes the SelectedIndex
property and when the ValueMember/DisplayMember property is set, it changes the SelectedIndex property according to the default values of the type bound to these properties(ValueMember/DisplayMember). Whereas setting the DataSource, at last, avoids the reinitialization of the properties. Do correct me, if I am wrong.
Some initialization must have occurred for the event to trigger as soon as it loads.
Which initialization triggers this event so fast?