c#列表覆盖问题 [英] c# list overwrite issue

查看:121
本文介绍了c#列表覆盖问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些如下所示的代码,它将 gridview 的值写入列表中,如下所示。
代码没有得到正确的值,但当网格的第二行被添加到列表中时,它将覆盖列表的第一行。

有人知道为什么会发生这种情况吗?

I have some code shown below that writes the values of a gridview to a list as shown. The code does get the correct values but when the second row of the grid is added to the list it overwrites the first row of the list.
Anybody know why this is happening?

C#代码

C# Code

 List<Item> lstNewItems = new List<Item>(); // Control Items  
 lstNewItems.Clear();
 Item NewItem = new Item();
 foreach (GridViewRow PendingItemUnderControl in GridViewPendingList.Rows)
 {
    NewItem.Paramater = PendingItemUnderControl.Cells[0].Text.ToLower();
    NewItem.Type = (String)Session["BrowseType"];
    lstNewItems.Add(NewItem);
 }


推荐答案

项目类。它发生在你的循环之前,所以实际上你正在研究同一个对象。您需要在循环内创建新实例(在每次迭代中):

You are creating one instance of Item class. It happens before your loop, so in reality you are working on the same object. You need to create new instance inside loop (in each iteration):

List<Item> lstNewItems = new List<Item>(); // Control Items  
lstNewItems.Clear();

foreach (GridViewRow PendingItemUnderControl in GridViewPendingList.Rows)
{
    Item NewItem = new Item();
    NewItem.Paramater = PendingItemUnderControl.Cells[0].Text.ToLower();
    NewItem.Type = (String)Session["BrowseType"];
    lstNewItems.Add(NewItem);
}

这篇关于c#列表覆盖问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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