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