微软官方文档上有很多示例,现截取一个:
// Create a DataSet with two tables and populate it.
private void MakeDataSet()
{
// Create a DataSet.
ds = new DataSet("myDataSet");
// Create two DataTables.
DataTable tCust = new DataTable("Customers");
DataTable tOrders = new DataTable("Orders");
// Create two columns, and add them to the first table.
DataColumn cCustID = new DataColumn("CustID", typeof(int));
DataColumn cCustName = new DataColumn("CustName");
tCust.Columns.Add(cCustID);
tCust.Columns.Add(cCustName);
// Create three columns, and add them to the second table.
DataColumn cID =
new DataColumn("CustID", typeof(int));
DataColumn cOrderDate =
new DataColumn("orderDate", typeof(DateTime));
DataColumn cOrderAmount =
new DataColumn("OrderAmount", typeof(decimal));
tOrders.Columns.Add(cOrderAmount);
tOrders.Columns.Add(cID);
tOrders.Columns.Add(cOrderDate);
// Add the tables to the DataSet.
ds.Tables.Add(tCust);
ds.Tables.Add(tOrders);
// Create a DataRelation, and add it to the DataSet.
DataRelation dr = new DataRelation
("custToOrders", cCustID, cID);
ds.Relations.Add(dr);
/* Populate the tables. For each customer and order,
create two DataRow variables. */
DataRow newRow1;
DataRow newRow2;
// Create three customers in the Customers Table.
for (int i = 1; i < 4; i++)
{
newRow1 = tCust.NewRow();
newRow1["custID"] = i;
// Add the row to the Customers table.
tCust.Rows.Add(newRow1);
}
// Give each customer a distinct name.
tCust.Rows[0]["custName"] = "Alpha";
tCust.Rows[1]["custName"] = "Beta";
tCust.Rows[2]["custName"] = "Omega";
// For each customer, create five rows in the Orders table.
for (int i = 1; i < 4; i++)
{
for (int j = 1; j < 6; j++)
{
newRow2 = tOrders.NewRow();
newRow2["CustID"] = i;
newRow2["orderDate"] = new DateTime(2001, i, j * 2);
newRow2["OrderAmount"] = i * 10 + j * .1;
// Add the row to the Orders table.
tOrders.Rows.Add(newRow2);
}
}
}
注:有不懂,找官方文档。