Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding item to List<> c#

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 ??

like image 517
Amd_eagle Avatar asked May 08 '26 22:05

Amd_eagle


2 Answers

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);

    }
like image 168
Rob Avatar answered May 11 '26 12:05

Rob


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);

    }
like image 32
R. Martinho Fernandes Avatar answered May 11 '26 11:05

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!