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

1 comment:

  1. Wow! Great post; I like how you have explained what a freelance developer's job is: to handle the work provided by their clients. Many platforms help developers to get good freelancing work to top developers. I came across Eiliana.com; it is a new and great platform for technical experts.

    ReplyDelete