![](/img/trans.png)
[英]How to fill different ComboBoxes in a DataGridView control with C#?
[英]C#: Using one Data Table in order to fill 2 different comboboxes?
我在名为combobox1和combobox2的表单(form1)上有2个组合框。
每个组合框应填充有存储在Sql Server 2005中2个不同表中的数据:table1和table2
我的意思是:combobox1-> table1 combobox2-> table2
我用适当的数据填充数据表,然后将组合框单独绑定到该表。
我的问题是:填充2个组合后,它们两个都具有来自table2的相等数据。
这是我的代码:
DataTable tb1 = new DataTable();
//Filling tb1 with data got from table1
combobox1.Items.Clear();
combobox1.DataSource = tb1;
combobox1.DisplayMember = "Name";
combobox1.ValueMember = "ID";
combobox1.SelectedIndex = -1;
//filling tb1 with data got from table2
combobox2.Items.Clear();
combobox2.DataSource = tb1;
combobox2.DisplayMember = "Name";
combobox2.ValueMember = "ID";
combobox2.SelectedIndex = -1;
怎么了?
看来,如果我得到2个不同的数据表(tb1和tb2),一切都会好起来的。
有任何建议请。
谢谢
DataTable
是引用类型,这意味着当您将tb1分配给控件的DataSource时,实际上是将内存中的引用/链接分配给DataSource
。 因此,当您修改tb1变量时,您是在更改引用本身。 因为仅更改引用,所以DataSource
仍然查看同一DataTable
,只是现在它具有不同的Data集。
在DataTable()上创建2个单独的DataView
,并将每个组合框绑定到DataView。
请参见DataView类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.