开发者

C#: Using one Data Table in order to fill 2 different comboboxes?

I have 2 comboboxes on a form (form1) called combobox1 and combobox2.

Each comboboxes should be filled with data stored in 2 different tables in Sql server 2005: table1 and table2

I mean: combobox1 --> table1 combobox2 --> table2

I fill data table with proper data and then bind the comboboxes to it separately.

My problem is: after filling 2 combos, both of them have equal data got from table2.

This is my code:

        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;

What's wrong?

It seems that if I get 2 different data tables (tb1 and tb2) , every thing will be all right.

Any suggestions please.

Thank you


DataTable is a reference type, which means that when you assign tb1 to the DataSource of a control, you are actually assigning a reference/link in memory to the DataSource. Therefor when you modify the tb1 variable you are changing the reference itself. Because you are only changing the reference, the DataSource still looks at the same DataTable, only now it has a different set of Data.


Create 2 separate DataView's on the DataTable(), and bind each combobox to a DataView,.

See DataView Class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜