動態建立資料
讀入 xml 資料檔private void button1_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32"))); fillRows(dt, 1, "product1", 1111); fillRows(dt, 2, "product2", 2222); ds.Tables.Add(dt); ds.Tables[0].TableName = "product"; //ds.WriteXml("Product.xml");//儲存成 xml 檔 this.dataGridView.Columns.Clear(); this.dataGridView.DataSource = ds; this.dataGridView.DataMember = "product"; } private void fillRows(DataTable dt, int pID, string pName, int pPrice) { DataRow dr; dr = dt.NewRow(); dr["Product_ID"] = pID; dr["Product_Name"] = pName; dr["product_Price"] = pPrice; dt.Rows.Add(dr); }
string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<employees>" + "<employee>" + "<name>shioulo</name>" + "<hireDate>2012-04-23</hireDate>" + "<title>Manager</title>" + "</employee>" + "</employees>"; //讀入 xml 資料 System.IO.StringReader reader = new System.IO.StringReader(xmlString); DataSet dataSet = new System.Data.DataSet(); dataSet.ReadXml(reader); //直接讀取檔案 dataSet.ReadXml("d:\\vs\\data.xml"); //透過 Reader 讀取檔案 XmlReader xml = XmlReader.Create("Product.xml", new XmlReaderSettings()); dataSet.ReadXml(xml);