【问题标题】:Explanation needed for strange behaviour of combobox组合框的奇怪行为需要解释
【发布时间】:2011-06-13 03:35:29
【问题描述】:

我只是在编写一个 Windows 应用程序,它从同一个数据源填充三个组合框。我的数据源是一个数据表。

我填充组合框的方式是为每个组合框重复以下代码:

'populate 1st combobox
cbx1.DataSource = table
cbx1.DisplayMember = "someColumn"
cbx1.ValueMember = "anotherColumn"
cbx1.SelectedIndex = Indx

'populate 2nd combobox
cbx2.DataSource = table
cbx2.DisplayMember = "someColumn"
cbx2.ValueMember = "anotherColumn"
cbx2.SelectedIndex = Indx

'populate 3rd combobox
cbx3.DataSource = table
cbx3.DisplayMember = "someColumn"
cbx3.ValueMember = "anotherColumn"
cbx3.SelectedIndex = Indx

当应用程序运行时,我从下拉列表中选择一个项目,例如 cbx1,我的选择也会反映在 cbx2 和 cbx3 中。我觉得这种行为很奇怪,如果有人能解释幕后发生的事情,我将不胜感激。

顺便说一句,我已经能够通过修改我的代码来规避这个问题,如下所示,但仍然希望对这种看似奇怪的行为进行解释。

'populate 1st combobox
Dim t1 as datatable = table.Copy
cbx1.DataSource = t1
cbx1.DisplayMember = "someColumn"
cbx1.ValueMember = "anotherColumn"
cbx1.SelectedIndex = Indx

'populate 2nd combobox
Dim t2 as datatable = table.Copy
cbx2.DataSource = t2
cbx2.DisplayMember = "someColumn"
cbx2.ValueMember = "anotherColumn"
cbx2.SelectedIndex = Indx

'populate 3rd combobox
Dim t3 as datatable = table.Copy
cbx3.DataSource = t3
cbx3.DisplayMember = "someColumn"
cbx3.ValueMember = "anotherColumn"
cbx3.SelectedIndex = Indx

【问题讨论】:

  • @Jose:是的,它是一个windows应用程序
  • 表实例还是一样的

标签: .net vb.net combobox datasource


【解决方案1】:

这种行为并不奇怪 - 您有三个组合框都绑定到同一个数据源,因此当您在第一个组合框中选择一个值时,您正在更改基础数据源中当前记录的索引 -由于其他两个组合框与此绑定,因此它们也会更新。

编辑:在幕后,这种行为的原因与 .Net 框架中数据绑定的实现方式有关 - 请参阅 this question 以获得更详细的说明。

正如您所发现的,解决方案是为每个组合框使用单独的数据源。有一个相关的问题here,您可能会觉得有趣。

【讨论】:

  • 感谢您的解释和链接,我现在很清楚这种行为
【解决方案2】:

这是因为您已将相同的数据表实例分配给组合框。

【讨论】:

  • 是的,我很怀疑,这就是为什么我能够以我的方式绕过它。但是,我更感兴趣的是在幕后发生的事情以表现出这种行为。我认为在组合框中选择一个项目不应该影响它的数据源。
猜你喜欢
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 2015-01-14
相关资源
最近更新 更多