C# DataColumn


  DataColumn 是用來模擬物理數據庫中的列。DataColumn 的組合組成了 DataTable 中列的架構。生成 DataTable 架構的方法就是向 DataColumnCollection 中添加DataColumn 對象來生成架構。同物理數據庫一樣,列是有類型的,比如 varchar, datatime, int 等, DataColumn 有 DataType 屬性表示這一列所存儲的數據種類。由於 DataTable 所包含的數據通常合並回其原始數據源,因此必須使其數據類型與數據源中的數據類型匹配。這個匹配關系,可以再 msdn 中的 《數據類型映射 (ADO.NET)》章節查詢到。

  在物理數據庫中,我們的列都要有各種約束來維持數據完整性,比如非空、唯一,同時也有各種自動化的操作,比如,自增。同樣的在內存中,我們也可以這樣定義,通過 AllowDBNull 、Unique 和 ReadOnly 等屬性對數據的輸入和更新施加限制,通過 AutoIncrement、AutoIncrementSeed 和 AutoIncrementStep 屬性來實現數據自動生成。

 


 

1.通過 DataColumn 創建列

  下面的示例用幾個 DataColumn 對象創建 DataTable

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); 
    } 
}

 

 2. 向數據表中添加列

   DataColumn 的主要作用就是添加到 DataTable 中。添加的方法有兩個:1. 顯示的使用構造函數,然后將引用添加到集合中。2. 表內創建 DataColumn 對象,也就是在集合中直接添加。以下示例向 DataTable 中添加了四列。

DataTable workTable = new DataTable("Customers");

DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

 

3. 定義主鍵

  在將一個單獨的 DataColumn 標識為 DataTable 的 PrimaryKey 時,表會自動將列的 AllowDBNull 屬性設置為 false,並將 Unique 屬性設置為 true。 如果是多列主鍵,則只有 AllowDBNull 屬性自動設置為 false。 

//一列
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]};

// Or

DataColumn[] columns = new DataColumn[1];
columns[0] = workTable.Columns["CustID"];
workTable.PrimaryKey = columns;
//多列
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustLName"], 
                                         workTable.Columns["CustFName"]};

// Or

DataColumn[] keyColumn = new DataColumn[2];
keyColumn[0] = workTable.Columns["CustLName"];
keyColumn[1] = workTable.Columns["CustFName"];
workTable.PrimaryKey = keyColumn;

4.創建 AutoIncrement 列

  只要將 AutoIncrement 屬性設置為 true。此列的值就會自動遞增了。可以設置遞增的初始值,和步進大小。同時,要把 ReadOnly 屬性設置為 true。

DataColumn workColumn = workTable.Columns.Add(
    "CustomerID", typeof(Int32));
workColumn.AutoIncrement = true;
workColumn.AutoIncrementSeed = 200;
workColumn.AutoIncrementStep = 3;

 


參考文獻:http://msdn.microsoft.com/zh-cn/library/system.data.datacolumn(v=vs.90)




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM