views:

28

answers:

2

Hi all.

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

+1  A: 

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

See DataView Class

Mitch Wheat
+2  A: 

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.

GenericTypeTea
ok, so you think I should have 2 different data tables for filling 2 combos?
odiseh
If you have similar Data, then Mitch's answer would be better. If you are pulling back two entirely different DataTables, then just declare two DataTables.
GenericTypeTea
Thank you, but why what you said above is NOT correct when we use string. I mean as we know, string is a reference type. string s = "hello";textbox1.Text = s;s = "world";textbox2.Text = s;In code snippet above, textbox1.Text has value "hello" and textbox2.Text has "world". right?
odiseh
Yes it is correct. String is pretty much an exception to the rule. check out this SO question here: http://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type. And here's an article on Value vs Reference types that might help you understand this fundamental part of the language: http://www.albahari.com/valuevsreftypes.aspx.
GenericTypeTea