我有一些代码如下所示,用于写入 a 的值gridview
到如图所示的列表。
该代码确实获得了正确的值,但是当网格的第二行添加到列表中时,它会覆盖列表的第一行。
有人知道为什么会发生这种情况吗?
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);
}
您正在创建一个实例Item
班级。它发生在循环之前,因此实际上您正在处理同一个对象。您需要在循环内创建新实例(在每次迭代中):
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)