DataColumn 类 (转)

From :  http://blog.csdn.net/lai123wei/article/details/3503983

 

DataColumn 是用于创建 DataTable 的架构的基本构造块。通过向 DataColumnCollection 中添加一个或多个 DataColumn 对象来生成这个架构。

每个 DataColumn 都有 DataType 属性,该属性确定 DataColumn 所包含的数据的种类。例如,可以将数据类型限制为整数、字符串或小数。由于 DataTable 所包含的数据通常合并回其原始数据源,因此必须使其数据类型与数据源中的数据类型匹配。有关更多信息,请参见 将数据提供程序数据类型映射到 .NET Framework 数据类型。

AllowDBNull、Unique 和 ReadOnly 等属性对数据的输入和更新施加限制,从而有助于确保数据完整性。还可以使用 AutoIncrement、AutoIncrementSeed 和 AutoIncrementStep 属性来控制数据自动生成。有关 AutoIncrement 列的更多信息,请参见 创建 AutoIncrement 列。有关更多信息,请参见 为表定义主键。

还可以通过创建一个 UniqueConstraint 并将其添加到 DataColumn 所属的 DataTable 的 ConstraintCollection 中,来确保 DataColumn 中的值是唯一的。有关更多信息,请参见 将约束添加到表。

若要创建 DataColumn 对象之间的关系,请创建 DataRelation 对象并将其添加到 DataSet 的 DataRelationCollection。

可以使用 DataColumn 对象的 Expression 属性来计算列中的值或创建聚合列。

 

用DataColumn 对象创建 DataTable

View Code
private void MakeTable()

    // Create a DataTable. 
    DataTable table = new DataTable("Product");

    // Create a DataColumn and set various properties. 
    DataColumn column = new DataColumn(); 
    column.DataType = System.Type.GetType("System.Decimal"); 
    column.AllowDBNull = false
    column.Caption = "Price"
    column.ColumnName = "Price"
    column.DefaultValue = 25

    // Add the column to the table. 
    table.Columns.Add(column); 

    // Add 10 rows and set values. 
    DataRow row; 
    for(int i = 0; i < 10; i++)
    { 
        row = table.NewRow(); 
        row["Price"] = i + 1

        // Be sure to add the new row to the 
        
// DataRowCollection. 
        table.Rows.Add(row); 
    } 
  //添加一个DataGridView控件this.dataGridView1.DataSource = table; 这样可以看到所创建的表
}

 

posted on 2012-11-18 17:49  至柔  阅读(200)  评论(0)    收藏  举报

导航