以编程方式将新行添加到DataTable C#

时间:2013-01-28 09:54:55

标签: c# datatable

我有一个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++;
    }

有任何帮助吗?

3 个答案:

答案 0 :(得分: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,你的目标是动态变量而不是静态变量,所以它再次进入循环导致例外..

答案 1 :(得分: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

答案 2 :(得分:0)

代码的通用版本,只需更改变量RowsToAdd的值即可添加任意数量的行。你不需要crate三个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);
   }
}