DekGenius.com
[ Team LiB ] Previous Section Next Section

13.2 Adding a Row

As with untyped DataSet objects, there are two ways to add a new row to a strongly typed DataSet. The first uses the NewTableNameRow( ) method of the strongly typed DataSet to return a reference to a TableNameRow object. The accessor properties are then used to assign values to the columns of the new row. Finally, the AddTableNameRow( ) method adds the new row to the DataTable. The following example demonstrates this method:

// strongly typed DataSet called Northwind containing the Orders table
Northwind.OrdersDataTable ordersTable = new Northwind.OrdersDataTable();
// create a new row object
Northwind.OrdersRow ordersRow = ordersTable.NewOrdersRow();
// use property accessors to set the column values for the row
ordersRow.CustomerID = "VINET";
ordersRow.EmployeeID = 1;

// ... set the rest of the fields

// add the row to the table
ordersTable.AddOrdersRow(ordersRow);

The following code sample shows how the same thing can be accomplished with an untyped DataSet:

DataTable ordersTable = new DataTable("Orders");
// ... code to define or retrieve the schema for the DataTable
DataRow ordersRow = ordersTable.NewRow();
ordersRow["CustomerID"] = "VINET";
ordersRow["EmployeeID"] = 1;

// ... set the rest of the fields

ordersTable.Rows.Add(ordersRow);

The second way to add a new row to a strongly typed DataSet is to use the AddTableNameRow( ) method. This method allows a row to be added to the DataSet using a single statement similar to the Add( ) method of the DataRowCollection when dealing with untyped DataSet objects. The main difference, aside from the simpler syntax, is that the method is strongly typed, allowing parameter data type errors to be caught at compilation time. The following example illustrates the second method for adding a row:

// strongly typed DataSet
Northwind.OrdersDataTable ordersTable = new Northwind.OrdersDataTable();

// add the row to the table
ordersTable.AddOrdersRow("VINET", 1, ... );

Again, the following code sample shows how the same thing can be accomplished using an untyped DataSet:

// untyped DataSet
DataTable ordersTable = new DataTable("Orders");

// ... code to define or retrieve the schema for the DataTable

// add the row to the table
ordersTable.Rows.Add(new Object[] {"VINET", 1, ...});
    [ Team LiB ] Previous Section Next Section