由于某种原因,combobox是相互关联的
我有以下代码来填充3个combobox:
private void PopulateDDLs() { SqlConnection connection; SqlCommand command; SqlDataReader reader; DataTable dt; using (connection = new SqlConnection("connection string here")) { using (command = new SqlCommand("sql query here", connection)) { connection.Open(); using (reader = command.ExecuteReader()) { dt = new DataTable(); dt.Load(reader); ddl1.ValueMember = "col1"; ddl1.DisplayMember = "col2"; ddl1.DataSource = dt; ddl2.ValueMember = "col1"; ddl2.DisplayMember = "col2"; ddl2.DataSource = dt; ddl3.ValueMember = "col1"; ddl3.DisplayMember = "col2"; ddl3.DataSource = dt; } connection.Close(); } } }
但是,当我执行该程序并从其中一个combobox中进行选择时,会自动从其他combobox中选择相同的值。 知道为什么会这样,以及如何阻止它发生更重要的事情?
如果我创建3个函数,每个combobox1个,那么一切正常。
此项目是使用VS2013使用.NET-4.0创建的Word 2010的Word文档级项目。
新改进的解决方案:
DataSource
不仅仅是数据。
隐藏的默认BindingSource
使ComboBox跟随。
为了避免这种耦合以及本答案第一版中的数据复制,您需要做的就是为每个ComboBox创建一个单独的BindingSource
。 这些共享DataTable
但每个都有自己的rowPointer:
BindingSource bS1, bS2, bS3; .. .. .. .. dt = new DataTable(); dt.Load(reader); bS1 = new BindingSource(); bS1.DataSource = dt; bS2 = new BindingSource(); bS2.DataSource = dt; bS3 = new BindingSource(); bS3.DataSource = dt; .. ddl1.DataSource = bS1 ; ddl2.DataSource = bS2 ; ddl3.DataSource = bS3 ; .. ..
现在ComboBox可以独立更改。
注意 :我的第一个版本有效,但做错了。 抱歉..!