WinForms ComboBox SelectedIndexChanged event and SelectedValue assignment.

I am using WinForms.ComboBox and wanted to handle SelectedIndexChanged events. I found that when DataSource is assigned adding each row caused SelectedIndexChanged.
It is a known and aknowledged by Microsoft problem and there are possible workarounds(e.g see http://www.bobpowell.net/ComboBinding.htm  or http://www.windowsitpro.com/Article/ArticleID/41825/41825.html ).


I desided that I don’t need to set DataSource but will use



lst.Items.Clear();
lst.Items.AddRange(coln.ToArray());


It helped with SelectedIndexChanged event not firing before user actually change the value.


The new problem was that  when  I programmatically set cmb.SelectedValue=value , selection of the combobox was not changed and SelectedIndex was still -1.


Checking System.Windows.Forms.ListControl.set_SelectedValue in Reflecter confirmed, that only for bounded controls ( dataManager != null) selection would be changed by assigning SelectedValue.


It seems that the best approach would be to temprary remove comboBox_SelectedIndexChanged event handler before data binding, assign DataSource,DisplayMember, ValueMember , assign SelectedValue and then add comboBox_SelectedIndexChanged event handler again.

Advertisements