今天无意间用到ImportRow()向DataTable中添加记录,代码如下:
private void AddAppendix(string fileName, string DbName)
{
DataTable dtAppendix = UpdateAppendix();
DataRow dr = dtAppendix.NewRow();
dr["Appendix"] = fileName;
dr["DbName"] = DbName;
dtAppendix.ImportRow(dr);
}
可是执行后发现dtAppendix中的记录并没有增加。可是将上述黄色代码换成dtAppendix.Rows.Add(dr);就可以了。后上网查了下资料弄清楚了原因。下面就说一下这两者的用法与区别及其适用情况。
1、首先,我们先说下DataTable.NewRow()方法,这个方法可以创建和表具有相同构架的DataRow(而且必须使用这个方法才能创建和原表一样构架的DataRow),并且这个新行是添加在原表上的。但是我发现这个DataTable中并没有这个空行。为什么?原因是这样的:原来Datatable中Rows都一个RowState属性,共有如下几种:
Detached | 该行已被创建,但不属于任何 DataRowCollection。DataRow 在以下情况下立即处于此状态:创建之后添加到集合中之前;或从集合中移除之后。 |
Unchanged | 该行自上次调用 AcceptChanges 以来尚未更改。 |
Added | 该行已添加到 DataRowCollection 中,AcceptChanges 尚未调用。 |
Deleted | |
Modified | 该行已被修改,AcceptChanges 尚未调用。 |
{
DataTable dtNew = dt.Clone();
foreach (DataRow dr in dt.Rows)
{
dtNew.ImportRow(dr);
}
return dtNew;
}
{
DataRowCollection rowCollection = table.Rows;
// Instantiate a new row using the NewRow method.
DataRow newRow = table.NewRow();
// Insert code to fill the row with values.
// Add the row to the DataRowCollection.
table.Rows.Add(newRow);
}
好,今天先写到这里!上述内容如有错误,麻烦纠正,谢谢!