为DataTable动态添加列

     public const string TEMP_TABLE_NAME = "Temp";
        public void CreateTempTableStructure(EmployeeDataSet.EmployeesALLDataTable employeeDataTable)
        {
            if (!this.Tables.Contains(TEMP_TABLE_NAME))
            {
                DataTable tempTable = new DataTable(TEMP_TABLE_NAME);
                foreach (DataColumn column in employeeDataTable.Columns)
                {
                    DataColumn dataColumn = new DataColumn();
                    dataColumn.DataType = typeof(string);
                    dataColumn.Caption = column.Caption;
                    dataColumn.ColumnName = column.ColumnName;                       
                    tempTable.Columns.Add(dataColumn);
                }
 
                foreach (InsuranceDataSet.InsuranceTypesRow insuranceTypeRow in InsuranceDataSet.GetCacheData().InsuranceTypes)
                {
                    DataColumn c1 = new DataColumn();
                    c1.DataType = typeof(string);
                    c1.Caption = insuranceTypeRow.Name + "/公司承担";
                    c1.ColumnName = "Column" + insuranceTypeRow.ID.Trim() + "1";
                    tempTable.Columns.Add(c1);
                    DataColumn c2 = new DataColumn();
                    c2.DataType = typeof(string);
                    c2.Caption = insuranceTypeRow.Name + "/个人承担";
                    c2.ColumnName = "Column" + insuranceTypeRow.ID.Trim() + "2";
                    tempTable.Columns.Add(c2);
                }
                this.Tables.Add(tempTable);
            }
        }

①、创建DataTable对象:DataTable tbl = new DataTable("TableName");

②、将DataTable添加到DataSet对象的Table集合

    DataSet ds = new DataSet();

    DataTable tbl = new DataTable("Customers");

    ds.Tables.Add(tbl);

 

    DataSet ds = new DataSet();

    DataTable tbl = ds.Tables.Add("Customers");

 DataTable对象只能存在于至多一个DataSet对象中。如果希望将DataTable添加到多个DataSet中,就必须使用Copy方法或Clone方法。Copy方法创建一个与原DataTable结构相同并且包含相同行的新DataTable;Clone方法创建一个与原DataTable结构相同,但没有包含任何行的新DataTable。

③、为DataTable添加列

    DataTable tbl = ds.Tables.Add("Orders");

    DataColumn col =tbl.Columns.Add("OrderID",typeof(int));

    col.AllowDBNull = false;

    col.MaxLength = 5;

    col.Unique = true;

    tbl.PrimaryKey = new DataColumn[]{tbl.Columns["CustomersID"]};

    当设置主键时,AllowDBNull自动设置为False;

④、处理自动增量列

    DataSet ds = new DataSet();

    DataTable tbl = ds.Tables.Add("Orders");

    DataColumn col = tbl.Columns.Add("OrderID",typeof(int));

    col.AutoIncrement = true;

    col.AutoIncrementSeed = -1;

    col.AutoIncrementStep = -1;

    col.ReadOnly = true;

⑤、添加基于表达式的列

    tbl.Columns.Add("ItemTotal",typeof(Decimal),"Quantity*UnitPrice");

posted on 2011-08-29 09:42  哈哈菜鸟  阅读(3617)  评论(0编辑  收藏  举报

导航