public DataTable CreateDataTable()
{
DataTable dt = new DataTable("testTable");//创建名字testTable的DataTable
DataColumn DcAutoId = new DataColumn("tId", typeof(int));
DcAutoId.AutoIncrement = true;//是否自动自增
DcAutoId.AutoIncrementSeed = 1;//起始值
DcAutoId.AutoIncrementStep = 1;//每次增加1
dt.Columns.Add(DcAutoId);
DataColumn dcUserName = new DataColumn("UserName", typeof(string));
dcUserName.AllowDBNull = false;//是否允许为空
dcUserName.DefaultValue = "www.luofenming.com";//该列得默认值
dt.Columns.Add(dcUserName);
dt.Columns.Add("UserAge", typeof(int));//也可以这样添加列
//-----给表行添加数据------------------------------------
//给表行添加数据方式1
DataRow dr1 = dt.NewRow();
dr1["UserName"] = "罗分明";
dr1["UserAge"] = 18;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["UserName"] = "lqwjve";
dr2["UserAge"] = 19;
int i = dr2.Table.Columns.Count;
dt.Rows.Add(dr2);
//给表行添加数据方式2,使用对象初始化器语法添加新行
dt.Rows.Add(null, "LuoFenMing", 19);
return dt;
}本文来自 www.luofenming.com