Skip to Content
.NET & XML
book

.NET & XML

by Niel M. Bornstein
November 2003
Intermediate to advanced
476 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from .NET & XML

Populating a DataSet

The DataSet is now ready to use just as if you had created it procedurally. You can create new rows in each of its tables, using the DataTable.NewRow( ) and DataTable.Rows.Add( ) methods, as shown in Example 11-5.

Example 11-5. Populating the DataSet
using System;
using System.Data;

public class CreateData {
  public static void Main(string [ ] args) {

    DataSet dataSet = new DataSet( );
    dataSet.ReadXmlSchema("Coupons.xsd");
    
    DataTable couponsTable = dataSet.Tables["coupons"];

    DataRow couponRow = couponsTable.NewRow( );
    couponRow["coupon_code"] = "763FF";
    couponRow["discount_amount"] = 0.5;
    couponRow["discount_type"] = DiscountType.Fixed;
    couponRow["expiration_date"] = new DateTime(2002,12,31);
    couponsTable.Rows.Add(couponRow);

    dataSet.WriteXml("Coupons.xml");
  }
}

Some important highlights of this program are listed below. First, a new DataSet instance is created, and its structure is populated with the saved Coupons.xsd schema:

DataSet dataSet = new DataSet( );
dataSet.ReadXmlSchema("Coupons.xsd");

Next, the “coupons” table is retrieved using the DataTableCollection’s string indexer:

DataTable couponsTable = dataSet.Tables["coupons"];

You can only create a new row using the DataTable’s NewRow( ) factory method. This is because the columns must be populated according to the database schema stored in the DataTable. Note that the NewRow( ) method does not actually add the new DataRow to the DataTable; that happens later:

DataRow couponRow = couponsTable.NewRow( );

Now ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Applied XML Programming for Microsoft® .NET

Applied XML Programming for Microsoft® .NET

Dino Esposito
XML Hacks

XML Hacks

Michael Fitzgerald

Publisher Resources

ISBN: 0596003978Supplemental ContentErrata