简体   繁体   中英

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

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

    }

change your code as below itwill work. You need to instantiate the object inside so that it will new every 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);

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM