DataTable. ImportRow () and DataTable. Rows. Add (), datatable. importrow
When writing code today, ImportRow () is used to add records to the DataTable. The Code is as follows:
DataTable dt = datatable;
DataRow dr = dt. NewRow ();
Dr ["FileName"] = fileName;
Dr ["DbName"] = DbName;
Dt. ImportRow (dr );
However, the records in dtAppendix are not added after execution. However, you can replace the above red Rows code with dt. Rows. Add (dr. Then I checked the information online to find out the reason. The following describes the usage and differences between the two and their applicability.
1. First, let's talk about DataTable. newRow () method. This method can be used to create a DataRow with the same schema as the table (and this method must be used to create a DataRow with the same schema as the original table ), the new row is added to the original table. However, I found that this blank row does not exist in this able. Why? The reason is as follows: the Rows in the original able have a RowState attribute. There are several types of attributes:
1, DetachedThis row has been created but does not belong to any DataRowCollection. DataRow is in this status immediately after being created or added to or removed from the collection.
2, UnchangedThis row has not been changed since the last AcceptChanges call.
3, AddedThis row has been added to DataRowCollection, and AcceptChanges has not been called.
4, DeletedThis row has been deleted through the Delete method of DataRow.
5, ModifiedThis row has been modified and AcceptChanges has not been called.
In fact, the RowState of the row created by NewRow () is Detached, and the newly created row is obviously invisible.
2. ImportRow ()
Copy DateRow to able to retain any attribute settings, initial values, and current values. However, when the RowState attribute of DataRow is Detached, the data cannot be copied. Therefore, the preceding red code is unavailable. Some people on the Internet say that the new row cannot be copied because it belongs to the original table. I think this is incorrect because of the row attribute. In fact, if we change the row attributes, the ImportRow () method is still feasible.
ImportRow () is generally used to copy data from one table to another. The instance code is as follows:
DataTable dtNew = dt. Clone ();
Foreach (DataRow dr in dt. Rows)
{
DtNew. ImportRow (dr );
} If you really want to use ImportRow (), you can first add an empty row to operate: DataTable dt = datatable;
DataRow dr = dt. NewRow ();
Dr ["FileName"] = fileName;
Dr ["DbName"] = DbName; dt. Row. add ();
Dt. ImportRow (dr); this operation is a bit superfluous and is not recommended!