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 New TableName Row( ) method of the strongly typed DataSet to return a reference to a TableName Row object. The accessor properties are then used to assign values to the columns of the new row. Finally, the Add TableName Row( ) 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 Add TableName Row( ) 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, ...}); 


ADO. NET in a Nutshell
ADO.NET in a Nutshell
ISBN: 0596003617
EAN: 2147483647
Year: 2005
Pages: 415

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net