开发者

Explanation needed for strange behaviour of combobox

I was just writing a windows application that populates three comboboxes from the same datasource. My datasource is a datatable.

The way i populate the comboboxes is by repeating the following code for each of the comboboxes:

'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

When the application is run, and I select an item from the dropdown list of, say, cbx1, my choice is reflected in cbx2 and cbx3 as well. I find this behaviour strange and will be grateful if anybody could explain what is going on here behind the scenes.

On a side note, I've been able to circumvent this problem by modifying my code as shown below, but would still like to have an explanation for this seemingly strange behaviour.

'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


The behaviour is not so strange - you have three combo boxes all bound to the same data source, so when you select a value in the first combo box, you are changing the index of the current record in the underlying data source - since the other two combo boxes are bound to this, they will update also.

Edit: Behind the scenes, the reason for the behaviour is to do with how data binding is implemented in the .Net framework - see this question for a more detailed explanation.

As you have discovered, the solution is to use separate data sources for each combo box. There is a related question here which you may find interesting.


It is because you have assigned the same instance of the datatable to the comboboxes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜