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;
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 ??
Move the declaration of
Testing Hello = new Testing();
Inside the loop
So you have;
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);
}
The problem is exactly as you said: you're adding the same element to the list three times. And you're changing it with each iteration, but it's always the same object. You should move the creation of the object into the cycle, in order to create a different object each time.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With