Inserting New Records into a Dataset
In order to add new records into a dataset, a new data row must be created and added to the DataRow collection of a data table. The following procedure details how to insert additional rows into a DataTable object in a dataset. For this example, it is assumed the ExistingTable is in a dataset and has two columns named FirstName and LastName.
To add new records to a typed or untyped dataset
- Call a data table's NewRow method to create a new, blank record.
This new record inherits its column structure from the data table's DataColumnCollection.
' Visual Basic Dim anyRow as DataRow = ExistingTable.NewRow // C# DataRow anyRow = ExistingTable.NewRow();
- Update the new row as if it were an existing record.
' Visual Basic anyRow(0) = "Jay" anyRow(1) = "Stevens" ' or anyRow("FirstName") = "Jay" anyRow("LastName") = "Stevens" // C# anyRow[0] = "Jay"; anyRow[1] = "Stevens"; // or anyRow["FirstName"] = "Jay"; anyRow["LastName"] = "Stevens"; - Add the new record to the table by calling the Add method of the DataRowCollection object.
' Visual Basic ExistingTable.Rows.Add(anyRow) // C# ExistingTable.Rows.Add(anyRow);
Inserting New Records with Typed Datasets
Typed datasets expose the column names as properties of the DataRow object.
To add new records using typed datasets
- The following example illustrates the same three steps above, except this time the code is modified for use with a typed dataset:
' Visual Basic Dim anyRow as DataRow = DatasetName.ExistingTable.NewRow anyRow.FirstName = "Jay" anyRow.LastName = "Stevens" ExistingTable.Rows.Add(anyRow) // C# DataRow anyRow = DatasetName.ExistingTable.NewRow(); anyRow.FirstName = "Jay"; anyRow.LastName = "Stevens"; ExistingTable.Rows.Add(anyRow);
See Also
Editing Data in a Table | Adding Data to a Table | Deleting a Row from a Table | NewRow | Add | Updating, Inserting, and Deleting Records in a Dataset | Code: Creating a New DataRow Based on an Existing DataTable (Visual Basic)