gpt4 book ai didi

c# - 以编程方式向 DataTable 添加新行 C#

转载 作者:行者123 更新时间:2023-12-02 05:16:31 25 4
gpt4 key购买 nike

我有一个从数据库中填充的数据表,后面的代码试图在每行之后再添加 3 行。下面是代码。但是在第 6 行我得到了

Exception of type 'System.OutOfMemoryException' was thrown.

  for (int i = 0; i < AlldaysList.Rows.Count; i++)
{
DataRow row;
row = AlldaysList.NewRow();
DataRow row1;
row1 = AlldaysList.NewRow();
DataRow row2;
row2 = AlldaysList.NewRow();

// Then add the new row to the collection.
row["scenarionid"] = DBNull.Value;
row["description"] = "";
row1["scenarionid"] = DBNull.Value;
row1["description"] = "";
row2["scenarionid"] = DBNull.Value;
row2["description"] = "";
AlldaysList.Rows.InsertAt(row, i + 1);
AlldaysList.Rows.InsertAt(row1, i + 2);
AlldaysList.Rows.InsertAt(row2, i + 3);
i++;
}

最佳答案

//This could be the problem
i < AlldaysList.Rows.Count

我想你应该有一个变量叫做 int rowCount = AlldaysList.Rows.Count;在循环之前..

the loop should be  for (int i = 0; i < rowCount; i++)

我之所以这样说是因为如果你在循环中添加 3 行,你的 AlldaysList.Rows.Count 会改变 +3,你的目标是动态变量而不是静态变量,所以它再次进入循环并且导致异常..

关于c# - 以编程方式向 DataTable 添加新行 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com