C#手动代码创建DataTable结构,并添加数据

首次发布:2017-09-10 11:12
2020-01-10 更新
        public DataTable CreateDataTable()
        {//转载请保留 http://www.luofenming.com/show.aspx?id=ART2017091000001
            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));//也可以这样添加列

            //-----给表行添加数据------------------------------------
            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);

            return dt;
        }