ADO.NET對象的構造(4)_DataColumn
2024-07-10 13:03:34
供稿:網友
菜鳥學堂:
datacolumn構造
n public sub new()’ 剛創建時,新的 datacolumn 對象沒有默認的 columnname 或 caption 屬性。但是,在添加到 datacolumncollection 時,就給予列默認名稱(“column1”、“column2”等等)。
n public sub new(byval columnname as string)
n public sub new(byval columnname as string,byval datatype as type)
n public sub new(byval columnname as string,byval datatype as type,byval expr as string)
n public sub new(byval columnname as string,byval datatype as type,byval expr as string,byval type as mappingtype)
參數
1. columnname 一個字符串,它表示要創建的列的名稱。如果設置為空引用(visual basic 中為 nothing)或空字符串 (""),則當添加到列集合中時,將提供一個默認名稱。
2. datatype 支持的 datatype。
3. expr 用于創建該列的表達式。
4. type mappingtype 值之一。指定如何映射 datacolumn。在獲取或設置 datacolumn 的 columnmapping 屬性時,使用 mappingtype 枚舉。在 dataset 上調用 writexml 方法以將數據和架構作為 xml 文檔寫出時,該屬性確定如何寫列的值。
成員名稱
說明
attribute
將列映射到 xml 屬性。
element
將列映射到 xml 元素。
hidden
將列映射到內部結構。
simplecontent
將列映射到 xmltext 節點。
datacolumn 是用于創建 datatable 的架構的基本構造塊。通過向 datacolumncollection 中添加一個或多個 datacolumn 對象來生成這個架構。
每個 datacolumn 都有 datatype 屬性,該屬性確定 datacolumn 所包含的數據的種類。例如,可以將數據類型限制為整數、字符串或小數。由于 datatable 所包含的數據通常合并回其原始數據源,因此必須使數據類型與數據源中的數據類型匹配。
諸如 allowdbnull、unique 和 readonly 之類的屬性對數據的輸入和更新施加限制,從而有助于確保數據完整性。還可以使用 autoincrement、autoincrementseed 和 autoincrementstep 屬性來控制數據自動生成。
還可以通過創建 uniqueconstraint 并將其添加到 datacolumn 所屬的 datatable 的 constraintcollection,以確保 datacolumn 中的值是唯一的。
若要創建 datacolumn 對象之間的關系,請創建 datarelation 對象并將其添加到 dataset 的 datarelationcollection。
可以使用 datacolumn 對象的 expression 屬性來計算列中的值或創建聚合列。
示例
private sub createcomputedcolumn(byval mytable as datatable)
dim mytable as datatable = new datatable("mytable")
dim mycolumn as datacolumn
dim dt as system.type
dim strexpr as string
mycolumn = new datacolumn("id")
with mycolumn
.datatype = system.type.gettype("system.int32")
.autoincrement = true
.autoincrementseed = 1
.autoincrementstep = 1
.readonly = true
end with
mytable.columns.add(mycolumn)
dt = system.type.gettype("system.int32")
mycolumn = new datacolumn("quantity", dt)
with mycolumn
.allowdbnull = false
end with
mytable.columns.add(mycolumn)
mycolumn = new datacolumn
mycolumn.datatype = system.type.gettype("system.decimal")
mycolumn.allowdbnull = false
mycolumn.caption = "price"
mycolumn.columnname = "price"
mycolumn.defaultvalue = 25
mytable.columns.add(mycolumn)
dt = system.type.gettype("system.decimal")
mycolumn = new datacolumn("tax", dt, "price * .0862")
with mycolumn
.autoincrement = false
.readonly = true
end with
mytable.columns.add(mycolumn)
dt = system.type.gettype("system.decimal")
strexpr = "price * quantity"
' create the column, setting the type to attribute.
mycolumn = new datacolumn("total", dt, strexpr, mappingtype.attribute)
mycolumn.autoincrement = false
mycolumn.readonly = true
mytable.columns.add(mycolumn)
end sub