O'Reilly logo

.NET & XML by Niel M. Bornstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required