2

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

引发了“System.OutOfMemoryException”类型的异常。

  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++;
    }
4

3 回答 3

4
//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 并且你的目标是动态变量而不是静态变量,所以它再次进入循环并导致异常..

于 2013-01-28T10:03:25.813 回答
1

我认为你应该这样做:

int origRowCount = AlldaysList.Rows.Count;
for (int i = 0; i < origRowCount; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        AlldaysList.Rows.InsertAt(MakeNewAlldaysRow(AlldaysList), i * 4 + j);
    }
}

// ....
// (separate method)
static DataRow MakeNewAlldaysRow(DataTable table)
{
    DataRow row = table.NewRow();
    row["scenarionid"] = DBNull.Value;
    row["description"] = "";

    return row;
}

由于行列表将增加,因此您需要在开始添加行之前记下行数。此外,插入位置将增加4,因此i * 4 + j.

于 2013-01-28T10:05:50.287 回答
0

您的代码的通用版本,您可以通过更改变量 RowsToAdd 的值来添加任意数量的行。您不需要创建三个 DataRow 变量(row,row1,row2)...

int RowsToAdd=3
int rowCount = AlldaysList.Rows.Count;
for (int i = 0; i < rowCount; i++)
{
   for (int j = 0; j < RowsToAdd; j++)
   {
     DataRow dr = AlldaysList.NewRow();
     dr["scenarionid"] = DBNull.Value;
     dr["description"] = "";

     AlldaysList.Rows.Add(dr);
   }
}
于 2014-10-01T07:50:34.557 回答