效果图:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace xml
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataSet vendorData = new DataSet("VendorData");
DataTable vendor = vendorData.Tables.Add("Vendor");
vendor.Columns.Add("Id", typeof(Guid));
vendor.Columns.Add("Name", typeof(string));
vendor.Columns.Add("Address1", typeof(string));
vendor.Columns.Add("Address2", typeof(string));
vendor.Columns.Add("City", typeof(string));
vendor.Columns.Add("State", typeof(string));
vendor.Columns.Add("ZipCode", typeof(string));
vendor.Columns.Add("Country", typeof(string));
vendor.PrimaryKey = new DataColumn[] { vendor.Columns["Id"] };
DataTable part = vendorData.Tables.Add("Part");
part.Columns.Add("Id", typeof(Guid));
part.Columns.Add("VendorId", typeof(Guid));
part.Columns.Add("PartCode", typeof(string));
part.Columns.Add("PartDescription", typeof(string));
part.Columns.Add("Cost", typeof(decimal));
part.Columns.Add("RetailPrice", typeof(decimal));
part.PrimaryKey = new DataColumn[] { part.Columns["Id"] };
vendorData.Relations.Add(
"vendor_part",
vendor.Columns["Id"],
part.Columns["VendorId"]);
DataRow vendorRow = null;
vendorRow = vendor.NewRow();
Guid vendorId = Guid.NewGuid();
vendorRow["Id"] = vendorId;
vendorRow["Name"] = "Tailspin Toys";
vendor.Rows.Add(vendorRow);
DataRow partRow = null;
partRow = part.NewRow();
partRow["Id"] = Guid.NewGuid();
partRow["VendorId"] = vendorId;
partRow["PartCode"] = "WGT1";
partRow["PartDescription"] = "Widget 1 Description";
partRow["Cost"] = 10.00;
partRow["RetailPrice"] = 12.32;
part.Rows.Add(partRow);
partRow = part.NewRow();
partRow["Id"] = Guid.NewGuid();
partRow["VendorId"] = vendorId;
partRow["PartCode"] = "WGT2";
partRow["PartDescription"] = "Widget 2 Description";
partRow["Cost"] = 9.00;
partRow["RetailPrice"] = 11.32;
part.Rows.Add(partRow);
//DataTable vendorTable = vendorData.Tables["Vendor"];
Navigate parent to children
//DataRow[] parts = vendorRow.GetChildRows("vendor_part");
//foreach (DataRow dr in parts)
//{
// textBox1.AppendText("Part: " + dr["PartCode"] + "/r/n");
//}
Navigate child to parent
//DataRow parentRow = part.Rows[1].GetParentRow("vendor_part");
//textBox1.AppendText("Vendor: " + parentRow["Name"] + "/r/n");
//vendorData.Relations["vendor_part"].Nested = true;
//foreach (DataTable dt in vendorData.Tables)
//{
// foreach (DataColumn dc in dt.Columns)
// {
// if (dc.DataType != typeof(Guid))
// dc.ColumnMapping = MappingType.Attribute;
// }
//}
vendorData.WriteXml(@"c:/vendors.xml", XmlWriteMode.IgnoreSchema);
vendorData.WriteXmlSchema(@"c:/vendorSchema.xsd");
textBox1.AppendText("Done");
this.dataGrid1.DataSource = vendorData;
}
}
}