通过编程C#将新行添加到DataTable [英] Add new rows to a DataTable programmatically C#
问题描述
我有一个DataTable,我要从数据库中填充它,而后面的代码要在每行之后再添加3行。下面是代码。但是在第六行,我抛出了'System.OutOfMemoryException'类型的异常。
I have a DataTable wich i fill it from database and the in code behind i am trying to add 3 rows more after each row. Below is the code. But at the 6th line i get 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的变量;
i think u should have a variable called int rowCount = AlldaysList.Rows.Count; before the loop..
the loop should be for (int i = 0; i < rowCount; i++)
我之所以这样说,是因为如果您在循环中添加3行,则AlldaysList.Rows.Count会发生变化+3和ur将动态变量而不是静态变量作为目标,因此它再次进入循环并导致异常。
The reason why i say this is because if u add 3 rows inside the loop ur AlldaysList.Rows.Count is changing by +3 and u r targeting a dynamic variable instead of a static one and so it goes into the loop again and causes an exception..
这篇关于通过编程C#将新行添加到DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!