1 Asp.net DataTable添加列和行的方法 2 方法一: 3 4 DataTable tblDatas = new DataTable("Datas"); 5 DataColumn dc = null; 6 dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); 7 dc.AutoIncrement = true;//自动增加 8 dc.AutoIncrementSeed = 1;//起始为1 9 dc.AutoIncrementStep = 1;//步长为110 dc.AllowDBNull = false;//11 12 dc = tblDatas.Columns.Add("Product", Type.GetType("System.String"));13 dc = tblDatas.Columns.Add("Version", Type.GetType("System.String"));14 dc = tblDatas.Columns.Add("Description", Type.GetType("System.String"));15 16 DataRow newRow;17 newRow = tblDatas.NewRow();18 newRow["Product"] = "大话西游";19 newRow["Version"] = "2.0";20 newRow["Description"] = "我很喜欢";21 tblDatas.Rows.Add(newRow);22 23 newRow = tblDatas.NewRow();24 newRow["Product"] = "梦幻西游";25 newRow["Version"] = "3.0";26 newRow["Description"] = "比大话更幼稚";27 tblDatas.Rows.Add(newRow);28 29 方法二:30 31 DataTable tblDatas = new DataTable("Datas");32 tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));33 tblDatas.Columns[0].AutoIncrement = true;34 tblDatas.Columns[0].AutoIncrementSeed = 1;35 tblDatas.Columns[0].AutoIncrementStep = 1;36 37 tblDatas.Columns.Add("Product", Type.GetType("System.String"));38 tblDatas.Columns.Add("Version", Type.GetType("System.String"));39 tblDatas.Columns.Add("Description", Type.GetType("System.String"));40 41 tblDatas.Rows.Add(new object[]{ null,"a","b","c"});42 tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });43 tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });44 tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });45 tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });46 47 方法三:48 DataTable table = new DataTable ();49 50 //创建table的第一列51 DataColumn priceColumn = new DataColumn();52 //该列的数据类型53 priceColumn.DataType = System.Type.GetType("System.Decimal");54 //该列得名称55 priceColumn.ColumnName = "price";56 //该列得默认值57 priceColumn.DefaultValue = 50;58 59 // 创建table的第二列60 DataColumn taxColumn = new DataColumn();61 taxColumn.DataType = System.Type.GetType("System.Decimal");62 //列名63 taxColumn.ColumnName = "tax";64 //设置该列得表达式,用于计算列中的值或创建聚合列65 taxColumn.Expression = "price * 0.0862";66 // Create third column.67 DataColumn totalColumn = new DataColumn();68 totalColumn.DataType = System.Type.GetType("System.Decimal");69 totalColumn.ColumnName = "total";70 //该列的表达式,值是得到的是第一列和第二列值得和71 totalColumn.Expression = "price + tax";72 73 // 将所有的列添加到table上74 table.Columns.Add(priceColumn);75 table.Columns.Add(taxColumn);76 table.Columns.Add(totalColumn);77 78 //创建一行79 DataRow row = table.NewRow();80 //将此行添加到table中81 table.Rows.Add(row);82 83 //将table放在试图中84 DataView view = new DataView(table);85 dg.DataSource = view;86 87 dg.DataBind();