Adding empty rows to a DataTable
For tables with a LOT of rows the better solution is to have a "table prefab". Lets see an example. We need to update 100k rows of the destination (DST) table. We have external source (SRC) table. And we know that some rows in SRC may be absent what means the columns of that particular rows are DBNULL. In case if we just merge SRC to DST the old data still will be in DST. So in order to clear that data we need first to slear all data from columns where data will be imported from SRC and save another data (which is actually taken from another source tables).
Using "For...Next" is not preferred - takes too much time. And I do next:
- create temporary table (TMP) with the only columns consisting PrimaryKey matching DST.PriaryKey (without any rows yett)
- merge data from DST to TMP - this will create just rows
- manually add columns matching SRC - this will create "empty" rows
- merge TMP to DST
- and then merge SRC to DST
Here is the code in VB:
Dim tmp As DataTable = New DataTable
Dim pk(dst.PrimaryKey.Length - 1) As DataColumn
For Each col As DataColumn In dst.PrimaryKey
pk(j) = tmp.Columns.Add(col.ColumnName, col.DataType)
j += 1
Next
tmp.PrimaryKey = pk
tmp.Merge(src, False, MissingSchemaAction.Ignore) 'add rows
For Each col As DataColumn In src.Columns 'add empty columns
If dst.Columns.Contains(col.ColumnName) _
AndAlso Not tmp.Columns.Contains(col.ColumnName) _
Then tmp.Columns.Add(col.ColumnName, col.DataType)
Next
dst.Merge(tmp, True, MissingSchemaAction.Ignore) 'clear destination columns
You cannot add multiple rows without loops. If you want to add n
rows to a DataTable
where all columns are "empty" use DataRowCollection.Add
without arguments:
for(int i = 0; i < n; i++)
table.Rows.Add(); // all fields get their default value
in your for loop, (obviously needs a forloop to add multiple rows), you want to use
for(int i = 0; i < n; i++)
table.Rows.Add();
if you know what you want to put in the row, you can tweak this code:
DataRow newBlankRow = theDataTable.NewRow();
theDataTable.Rows.InsertAt(newBlankRow, theDataTable.Rows.Count);