C# 内存建表备忘

#region=====建表=====
        DataSet dataSet;
        // 创建表
        DataTable table = new DataTable("testTable");
        private void testTable()
        {
            //声明列 行
            DataColumn column;
            DataRow row;

            // 创建主要列  
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "Id";
            column.ReadOnly = true;
            column.Unique = true;
            table.Columns.Add(column);

            // 创建字符串型的列
            string[] colStr = new string[] { "FullName", "Code", "Department", "Manager", "Mobile", "Status", "ImgPath" };
            foreach (string s in colStr)
            {
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = s;
                column.AutoIncrement = false;
                column.ReadOnly = false;
                column.Unique = false;
                table.Columns.Add(column);
            }

            //  创建时间型的列
            string[] colDate = new string[] { "StartDate", "PlanEndDate" };
            foreach (string s in colDate)
            {
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.DateTime");
                column.ColumnName = s;
                column.AutoIncrement = false;
                column.ReadOnly = false;
                column.Unique = false;
                table.Columns.Add(column);
            }


            //Id 列作为主键
            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = table.Columns["Id"];
            table.PrimaryKey = PrimaryKeyColumns;

            dataSet = new DataSet();
            dataSet.Tables.Add(table);

            for (int i = 1; i <= 5; i++)
            {
                row = table.NewRow();
                row["Id"] = i;
                foreach (string s in colStr)
                {

                    if (s == "ImgPath")
                    {
                        row[s] = "Img/" + i + ".jpg";
                    }
                    else
                    {
                        row[s] = s + " - " + i;
                    }
                }
                foreach (string s in colDate)
                {
                    row[s] = DateTime.Now;
                }
                table.Rows.Add(row);
            }
        }
        #endregion
posted @ 2016-06-13 17:07  Tirisfal  阅读(374)  评论(0编辑  收藏  举报