有关将新项目添加到列表的任何想法c# [英] Any ideas on Adding new item to List c#

查看:52
本文介绍了有关将新项目添加到列表的任何想法c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组,我正在尝试将其写入列表,以便可以将其与数据网格绑定.
以下是我的代码.

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>


可以看到,当我的数组包含3行时,数据网格显示3行具有相同的数据,而不是3个不同的数据.我猜是我要向列表中添加Hello的次数是3次.
但是我是否将Hello更改为variabele,以便每次for循环循环其另一个名称时.
Ne Ideas ??


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

推荐答案

是的,您只是将同一对象引用添加了三次. ; P for循环的最后一次运行将所有行的值设置为您将看到的值,因为所有行均指向同一Testing实例.

你真的很亲近相反,请执行以下操作:

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;



可以将Testing变量Hello的作用域仅限定在for循环内.实际上,这就是您将获得新对象引用以添加到列表中的方式.



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.


这篇关于有关将新项目添加到列表的任何想法c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆