组合框被链接出于某种原因组合、原因、链接

2023-09-08 09:02:09 作者:  __&谜魂计? | __&谜魂计?

我有以下的code填充3组合框:

I have the following code to populate 3 comboboxes:

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();
        }
    }
}

然而,当我执行该程序,并从组合框的一个选择,相同的值被自动从另一个组合框选择。任何想法,为什么这种情况正在发生以及如何发生更重要的是阻止它?

However, when I execute this program, and make a selection from one of the comboboxes, the same value automatically gets selected from the other comboboxes. Any idea why this is happening and how to stop it from happening more importantly?

如果我创建3个功能,1为每个组合框,然后一切工作正常。

If I create 3 functions, 1 for each combobox, then everything works fine.

这个项目是使用.NET 4.0版本使用VS2013创建的Word 2010中的Word文档级的项目。

This project is a Word Document level project for Word 2010 created using .NET-4.0 using VS2013.

推荐答案

新大为改善的解决方案:

看起来像有隐藏默认的BindingSource,使组合框跟随。

Looks like there is hidden default BindingSource that makes the ComboBoxes follow.

要避免这种耦合,也是数据复制在这个答案的第一个版本,你需要做的就是创建一个单独的的BindingSource 每个组合框。这些共享数据表但每一个自己的rowPointer:

To avoid this coupling and also the data replication in the first version of this answer, all you need to do is create a separate BindingSource for each ComboBox. These share the DataTable but have each its own 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 ;
..
..

现在的组合框可以独立改变。

Now the ComboBoxes can be changed independently.

注意:我的第一个版本的工作,但就是在错误办法做到这一点。对不起..!

Note: My first version worked but was the wrong way do it. Sorry..!

 
精彩推荐