组合框由于某种原因被链接 [英] Comboboxes are linked for some reason

查看:28
本文介绍了组合框由于某种原因被链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来填充 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.

此项目是 Word 2010 的 Word 文档级项目,使用 .NET-4.0 和 VS2013 创建.

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

推荐答案

全新改进的解决方案:

DataSource 不仅仅是数据.

隐藏的默认 BindingSource 使 ComboBox 跟随.

There is hidden default BindingSource that makes the ComboBoxes follow.

为了避免这种耦合以及本答案第一个版本中的数据复制,您需要做的就是为每个 ComboBox 创建一个单独的 BindingSource.它们共享 DataTable 但每个都有自己的 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..!

这篇关于组合框由于某种原因被链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆