【发布时间】:2012-11-02 07:20:06
【问题描述】:
我在向DataTable 添加新行时遇到了这个奇怪的问题。它不会每次都发生,但是在运行应用程序时,我得到空引用异常,而没有找到空对象。
代码如下:
先清空DataTable的行列:
dtLibraries.Rows.Clear();
dtLibraries.Columns.Clear();
dtLibraries.Columns.Add("Col1");
dtLibraries.Columns.Add("Col2");
dtLibraries.Columns.Add("Col3");
dtLibraries.Columns.Add("Col4");
dtLibraries.Columns.Add("Col5");
dtLibraries.Columns.Add("Col6");
dtLibraries.Columns.Add("Col7");
dtLibraries.Columns.Add("Col8");
dtLibraries.Columns.Add("Col9");
然后读取另一个 DataTable 并将数据写入此表:
for (int s = 0; s <= dttemp.Rows.Count - 1; s++)
{
dttemp1.Clear();
dttemp1 = business.GetOutputLibraries("SimObjectOutputRequestSet",
dttemp.Rows[s].ItemArray[2].ToString(),
dttemp.Rows[s].ItemArray[1].ToString(), dttemp.Rows[s].ItemArray[0].ToString());
for (int j = 0; j <= dttemp1.Rows.Count - 1; j++)
{
DataRow dr = dtLibraries.NewRow();
dr["Col1"] = dttemp1.Rows[j].ItemArray[0].ToString();
dr["Col2"] = dttemp1.Rows[j].ItemArray[1].ToString();
dr["Col3"] = dttemp1.Rows[j].ItemArray[2].ToString();
dr["Col4"] = dttemp.Rows[s].ItemArray[0].ToString();
dr["Col5"] = dttemp.Rows[s].ItemArray[2].ToString();
dr["Col6"] = dttemp.Rows[s].ItemArray[1].ToString();
dr["Col7"] = cmbObject.Text.ToString();
dr["Col8"] = cmbLibraryType.Text;
dr["Col9"] = cmbLibrarySubType.Text;
dtLibraries.Rows.Add(dr); /// Exception occurs on this line
}
}
堆栈跟踪:
at System.Data.NameNode.Eval(DataRow row, DataRowVersion version)
at System.Data.BinaryNode.EvalBinaryOp(Int32 op, ExpressionNode left, ExpressionNode right, DataRow row, DataRowVersion version, Int32[] recordNos)
at System.Data.BinaryNode.Eval(DataRow row, DataRowVersion version)
at System.Data.DataExpression.Invoke(DataRow row, DataRowVersion version)
at System.Data.Index.AcceptRecord(Int32 record, IFilter filter)
at System.Data.Index.ApplyChangeAction(Int32 record, Int32 action, Int32 changeRecord)
at System.Data.Index.RecordStateChanged(Int32 record, DataViewRowState oldState, DataViewRowState newState)
at System.Data.DataTable.RecordStateChanged(Int32 record1, DataViewRowState oldState1, DataViewRowState newState1, Int32 record2, DataViewRowState oldState2, DataViewRowState newState2)
at System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Boolean suppressEnsurePropertyChanged, Int32 position, Boolean fireEvent, Exception& deferredException)
at System.Data.DataTable.InsertRow(DataRow row, Int64 proposedID, Int32 pos, Boolean fireEvent)
at System.Data.DataRowCollection.Add(DataRow row)
【问题讨论】:
-
什么是 dttemp1?哪一行恰好出现错误执行?
-
您的 StackTrace 没有详细信息,例如哪个方法调用引发了异常、发生了哪个方法异常等。
-
@Selalu_Ingin_Belajar:这是另一个
DataTable。我正在将该 dataTable 值转换为字符串,所以我认为这不会导致错误。 -
@dotNETbeginner:这是异常 strackTrace,我删除了最后一行,这与问题无关。
-
为什么不单步执行代码,看看异常发生在哪一行?它会帮助我们帮助你(充其量你会找到答案)=)