asp DataTable添加列和行的三种方法
程序员文章站
2024-03-08 15:24:16
复制代码 代码如下: #region 方法一: datatable tbldatas = new datatable("datas"); datacolumn dc = n...
复制代码 代码如下:
#region 方法一:
datatable tbldatas = new datatable("datas");
datacolumn dc = null;
dc = tbldatas.columns.add("id", type.gettype("system.int32"));
dc.autoincrement = true;//自动增加
dc.autoincrementseed = 1;//起始为1
dc.autoincrementstep = 1;//步长为1
dc.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);
#endregion
复制代码 代码如下:
#region 方法二:
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" });
#endregion
复制代码 代码如下:
#region 方法三:
datatable table = new datatable();
//创建table的第一列
datacolumn pricecolumn = new datacolumn();
pricecolumn.datatype = system.type.gettype("system.decimal");//该列的数据类型
pricecolumn.columnname = "price";//该列得名称
pricecolumn.defaultvalue = 50;//该列得默认值
// 创建table的第二列
datacolumn taxcolumn = new datacolumn();
taxcolumn.datatype = system.type.gettype("system.decimal");
taxcolumn.columnname = "tax";//列名
taxcolumn.expression = "price * 0.0862";//设置该列得表达式,用于计算列中的值或创建聚合列
// 创建table的第三列
datacolumn totalcolumn = new datacolumn();
totalcolumn.datatype = system.type.gettype("system.decimal");
totalcolumn.columnname = "total";
totalcolumn.expression = "price + tax";//该列的表达式,是第一列和第二列值得和
// 将所有的列添加到table上
table.columns.add(pricecolumn);
table.columns.add(taxcolumn);
table.columns.add(totalcolumn);
//创建一行
datarow row = table.newrow();
table.rows.add(row);//将此行添加到table中
//将table放在试图中
dataview view = new dataview(table);
//绑定到datagrid
dg.datasource = view;
dg.databind();
#endregion
推荐阅读