Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c# - Comboboxes are linked for some reason

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?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

New much improved solution:

A DataSource is more than just the data.

There is hidden default BindingSource that makes the ComboBoxes follow.

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..!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...