Wednesday, June 6, 2012

Winforms ListControls (ListBox or ComboBox) binding performance gotcha

PROBLEM: Excessive rebinding can occur with ListControls in Winforms.

SOLUTION: Specifically when the DataSource is changed, or when DisplayMember or ValueMember is changed after DataSource has been set, the binding infrastructure forces the control to rebind. Logically, this makes sense. But it poses a problem if you handle certain control events, in particular SelectedIndexChanged and SelectedValueChanged. In the worst case, the following simple sequence will raise SelectedIndexChanged three times in a row:
listbox.DataSource = dataTable
listbox.ValueMember = "id"
listbox.DisplayMember = "name"

Not a big deal if nothing data intensive is happening in SelectedIndexChanged but in my case it often calls the code to call a webservice. So simply changing the order of these to be as below results in just one SelectedIndexChanged call instead of 3, and hence one webservice call instead of 3.

listbox.DisplayMember = "name"
listbox.ValueMember = "id"
listbox.DataSource = dataTable

This very smart fellow discusses it in full on codeproject: http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx