WinForms - VB.NET - Passing same list as DataSource for two different listboxes create problems
Check out the simple code below :
Public Class Form1
Private _items 开发者_StackOverflow社区As List(Of String) = New List(Of String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_items.Add("Item1")
_items.Add("Item2")
_items.Add("Item3")
ListBox1.DataSource = _items
ListBox2.DataSource = _items
End Sub
End Class
What happens is that when the Item2 is selected in the first listbox, the second listbox automatically changes its selected item to the Item2. This happens just the same with the other listbox.
Any idea why this is happening?
That's because your two ListBoxes are sharing the form's default BindingContext object. To change this, explicitly create a BindingContext for each ListBox.
Yes that will happen. When you bind a DataSource to a control, the control binds itself to DataSource's events and calls its methods internally. Events like SelectionChanged, CurrentRecordChanged (not sure of the exact names) are fired by the DataSource.
For e.g. when you select an item in ListBox1, the listbox changes the current record pointer in the DataSource which inturn generates in event like CurrentRecordChanged. This event is captured by listbox2 (also by listbox1) and it changes its current record.
Try this
using System.Linq;
ListBox1.DataSource = _items.ToArray();
ListBox2.DataSource = _items.ToArray();
精彩评论