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

        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;//是否允许为空
            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;
        }

评论