Check out the simple code below :
看看下面的简单代码:
Public Class Form1
Private _items 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.
会发生的情况是,当在第一个列表框中选择Item2时,第二个列表框会自动将其选定的项目更改为Item2。这与其他列表框的情况完全相同。
Any idea why this is happening?
知道为什么会这样吗?
3 个解决方案
#1
3
That's because your two ListBoxes are sharing the form's default BindingContext object. To change this, explicitly create a BindingContext for each ListBox.
那是因为你的两个ListBox共享表单的默认BindingContext对象。要更改此设置,请为每个ListBox显式创建BindingContext。
#2
1
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.
是的,这将发生。将DataSource绑定到控件时,控件将自身绑定到DataSource的事件并在内部调用其方法。 SelectionChanged,CurrentRecordChanged(不确定名称)等事件由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.
对于例如当您在ListBox1中选择一个项目时,列表框会更改DataSource中的当前记录指针,该指针在CurrentRecordChanged等事件中生成。 listbox2(也是listbox1)捕获此事件,并更改其当前记录。
#3
1
Try this
尝试这个
using System.Linq;
ListBox1.DataSource = _items.ToArray();
ListBox2.DataSource = _items.ToArray();
#1
3
That's because your two ListBoxes are sharing the form's default BindingContext object. To change this, explicitly create a BindingContext for each ListBox.
那是因为你的两个ListBox共享表单的默认BindingContext对象。要更改此设置,请为每个ListBox显式创建BindingContext。
#2
1
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.
是的,这将发生。将DataSource绑定到控件时,控件将自身绑定到DataSource的事件并在内部调用其方法。 SelectionChanged,CurrentRecordChanged(不确定名称)等事件由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.
对于例如当您在ListBox1中选择一个项目时,列表框会更改DataSource中的当前记录指针,该指针在CurrentRecordChanged等事件中生成。 listbox2(也是listbox1)捕获此事件,并更改其当前记录。
#3
1
Try this
尝试这个
using System.Linq;
ListBox1.DataSource = _items.ToArray();
ListBox2.DataSource = _items.ToArray();