Bound ListBox SelectedIndex keeps changing
I have a ListBox that is bound to a List. Every-time the Lis开发者_开发知识库tBox updates to reflect the collection, the SelectedIndex changes to the top item. How can stop this behavior and retain the current SelectedIndex?
[UPDATE]
I found a better collection to use for this kind of functionality - the 'BindingList': http://msdn.microsoft.com/en-us/library/ms132679(v=VS.90).aspx.
WulfgarPro.
When [...] updates to reflect the collection
Does that mean there is a new collection? If so what does "the same position" mean?
When re-binding to a(nother) list, you will have to save & restore the index position. Just write code around the place where you update the DataSource.
Using the BindingList collection rather than a List remedied a lot of my problems. I was originally using a Thread and a Delegate to query the collection and call ListBox.DataSource=[..] to update the binding. This was slow, cumbersome and error prone. Not to mention my original problem of not being able to easily retain the SelectedItem. Changing to to the BindingList allowed me to remove the thread and delegate and now everything works as intended. Assigning the desired display property for the ListBox can be achieved using ListBox.DisplayMember=[..].
WulfgarPro.
精彩评论