方法一:
DataTable tblDatas = new DataTable("Datas");
DataColumn dc = null;dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));dc.AutoIncrement = true;//自动增加dc.AutoIncrementSeed = 1;//起始为1dc.AutoIncrementStep = 1;//步长为1dc.AllowDBNull = false;//dc = tblDatas.Columns.Add("Product", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("Version", Type.GetType("System.String"));dc = tblDatas.Columns.Add("Description", Type.GetType("System.String"));DataRow newRow;
newRow = tblDatas.NewRow();newRow["Product"] = "水果刀";newRow["Version"] = "2.0";newRow["Description"] = "打架专用";tblDatas.Rows.Add(newRow);newRow = tblDatas.NewRow();
newRow["Product"] = "折叠凳";newRow["Version"] = "3.0";newRow["Description"] = "行走江湖七武器之一";tblDatas.Rows.Add(newRow); 方法二: //创建datatable 的一个示例 DataTable tblDatas = new DataTable("Datas"); tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); //创建一列,自动增长 tblDatas.Columns[0].AutoIncrement = true; tblDatas.Columns[0].AutoIncrementSeed = 1; tblDatas.Columns[0].AutoIncrementStep = 1;tblDatas.Columns.Add("Product", Type.GetType("System.String")); //创建一列
tblDatas.Columns.Add("Version", Type.GetType("System.String")); tblDatas.Columns.Add("Description", Type.GetType("System.String"));tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); //创建一行
tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });
//2,在DataTable中添加两列 时间
DataColumn dc1 = new DataColumn("Year"); DataColumn dc2 = new DataColumn("Month"); dt.Columns.Add(dc1); dt.Columns.Add(dc2); //给新添加的两列添加数据 for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; dr.BeginEdit(); dr["Year"] = "2009" dr["Month"] = "10"; dr.EndEdit(); dt.AcceptChanges(); }