Click here to Skip to main content
16,019,740 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
i have an 2D array which i am trying to write into a List so i can bind it with a datagrid.
below is my code.

string[,] array = new string[8,4];
 array[counting2, 0] = txtSend.Text;
 array[counting2, 1] = One;
 array[counting2, 2] = Two;
 array[counting2, 3] = Three;

 List<testing> Hello1 = new List<testing>();

 Testing Hello = new Testing();
 for (int i = 0; i <= counting2;i++ )
 {
     Hello.year = array[counting2, 0];
     Hello.One = array[counting2, 1];
     Hello.Two = array[counting2, 2];
     Hello.Three = array[counting2, 3];
     Hello1.Add(Hello);

 }
dataGrid1.ItemsSource = Hello1;</testing></testing>

What is see is when my array contain 3 rows the data grids shows 3 rows with the same data instead of 3 diffrent data. I am guessing is that i am adding Hello to the list 3 times.
But do i change the Hello to a variabele so each time the for loop loops its another name.
Ne Ideas ??
Posted
Updated 1-Mar-11 17:03pm
v3

1 solution

Yes, you're just adding the same object reference three times. ;P The last run on the for loop sets the values to what you'll see for all rows, since all rows point to the same instance of Testing.

You were really close. Instead, do this:

for (int i = 0; i <= counting2;i++ )
{
    Testing Hello = new Testing();
    Hello.year = array[counting2, 0];
    Hello.One = array[counting2, 1];
    Hello.Two = array[counting2, 2];
    Hello.Three = array[counting2, 3];

    Hello1.Add(Hello);
}
dataGrid1.ItemsSource = Hello1;


It's okay to have the Testing variable Hello scoped only within the for loop. In fact, this is how you'll get a new object reference to add to the list.
 
Share this answer
 
Comments
Amd_eagle 1-Mar-11 23:44pm    
Its Still the same i have n rows in the Grid with the same values in all n grids.
Amd_eagle 2-Mar-11 0:10am    
Thank You so much your code helped and always i ahd to delcare the array globaly otherwise i keep getting blank data except for the latest
thax a lot :-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900