DataTable 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
代表一個記憶體內資料表。
public ref class DataTable : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitialize, System::ComponentModel::ISupportInitializeNotification, System::Runtime::Serialization::ISerializable, System::Xml::Serialization::IXmlSerializable
public ref class DataTable
public ref class DataTable : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitialize, System::Runtime::Serialization::ISerializable
public ref class DataTable : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitializeNotification, System::Runtime::Serialization::ISerializable, System::Xml::Serialization::IXmlSerializable
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
public class DataTable
[System.Serializable]
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)>]
type DataTable = class
inherit MarshalByValueComponent
interface IListSource
interface ISupportInitialize
interface ISupportInitializeNotification
interface ISerializable
interface IXmlSerializable
type DataTable = class
inherit MarshalByValueComponent
interface IListSource
interface ISupportInitialize
interface ISupportInitializeNotification
interface ISerializable
interface IXmlSerializable
type DataTable = class
[<System.Serializable>]
type DataTable = class
inherit MarshalByValueComponent
interface IListSource
interface ISupportInitialize
interface ISerializable
[<System.Serializable>]
type DataTable = class
inherit MarshalByValueComponent
interface IListSource
interface ISupportInitializeNotification
interface ISupportInitialize
interface ISerializable
interface IXmlSerializable
Public Class DataTable
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitialize, ISupportInitializeNotification, IXmlSerializable
Public Class DataTable
Public Class DataTable
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitialize
Public Class DataTable
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitializeNotification, IXmlSerializable
- 繼承
- 繼承
-
DataTable
- 衍生
- 屬性
- 實作
範例
此範例示範如何使用特定架構定義手動建立 DataTable:
- 建立多個 DataTable 並定義初始數據行。
- 建立數據表條件約束。
- 插入值並顯示數據表。
- 建立表達式數據行並顯示數據表。
using System;
using System.Data;
class Program
{
static void Main()
{
// Create two tables and add them into the DataSet.
DataTable orderTable = CreateOrderTable();
DataTable orderDetailTable = CreateOrderDetailTable();
DataSet salesSet = new();
salesSet.Tables.Add(orderTable);
salesSet.Tables.Add(orderDetailTable);
// Set the relations between the tables
// and create the related constraint.
salesSet.Relations.Add(
"OrderOrderDetail",
orderTable.Columns["OrderId"],
orderDetailTable.Columns["OrderId"],
true);
Console.WriteLine("After creating the foreign key constraint, " +
"you'll see the following error if you insert " +
"an order detail with the wrong OrderId:\n");
try
{
DataRow errorRow = orderDetailTable.NewRow();
errorRow[0] = 1;
errorRow[1] = "O0007";
orderDetailTable.Rows.Add(errorRow);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
// Insert the rows into the table.
InsertOrders(orderTable);
InsertOrderDetails(orderDetailTable);
Console.WriteLine("The initial Order table.");
ShowTable(orderTable);
Console.WriteLine("The OrderDetail table.");
ShowTable(orderDetailTable);
// Use the Aggregate-Sum on the child table column to get the result.
DataColumn colSub = new("SubTotal", typeof(decimal), "Sum(Child.LineTotal)");
orderTable.Columns.Add(colSub);
// Compute the tax by referencing the SubTotal expression column.
DataColumn colTax = new("Tax", typeof(decimal), "SubTotal*0.1");
orderTable.Columns.Add(colTax);
// If the OrderId is 'Total', compute the amount due on all orders; otherwise, compute the amount due on this order.
DataColumn colTotal = new(
"TotalDue",
typeof(decimal),
"IIF(OrderId='Total',Sum(SubTotal)+Sum(Tax),SubTotal+Tax)");
orderTable.Columns.Add(colTotal);
DataRow row = orderTable.NewRow();
row["OrderId"] = "Total";
orderTable.Rows.Add(row);
Console.WriteLine("The Order table with the expression columns.");
ShowTable(orderTable);
Console.WriteLine("Press any key to exit.....");
Console.ReadKey();
}
private static DataTable CreateOrderTable()
{
DataTable orderTable = new("Order");
// Define the columns one at a time.
DataColumn colId = new("OrderId", typeof(string));
orderTable.Columns.Add(colId);
DataColumn colDate = new("OrderDate", typeof(DateTime));
orderTable.Columns.Add(colDate);
// Set the OrderId column as the primary key.
orderTable.PrimaryKey = [colId];
return orderTable;
}
private static DataTable CreateOrderDetailTable()
{
DataTable orderDetailTable = new("OrderDetail");
// Define all the columns at once.
DataColumn[] cols =
[
new DataColumn("OrderDetailId", typeof(int)),
new DataColumn("OrderId", typeof(string)),
new DataColumn("Product", typeof(string)),
new DataColumn("UnitPrice", typeof(decimal)),
new DataColumn("OrderQty", typeof(int)),
new DataColumn("LineTotal", typeof(decimal), "UnitPrice*OrderQty")
];
orderDetailTable.Columns.AddRange(cols);
orderDetailTable.PrimaryKey = [orderDetailTable.Columns["OrderDetailId"]];
return orderDetailTable;
}
private static void InsertOrders(DataTable orderTable)
{
// Add one row at a time.
DataRow row1 = orderTable.NewRow();
row1["OrderId"] = "O0001";
row1["OrderDate"] = new DateTime(2013, 3, 1);
orderTable.Rows.Add(row1);
DataRow row2 = orderTable.NewRow();
row2["OrderId"] = "O0002";
row2["OrderDate"] = new DateTime(2013, 3, 12);
orderTable.Rows.Add(row2);
DataRow row3 = orderTable.NewRow();
row3["OrderId"] = "O0003";
row3["OrderDate"] = new DateTime(2013, 3, 20);
orderTable.Rows.Add(row3);
}
private static void InsertOrderDetails(DataTable orderDetailTable)
{
// Use an Object array to insert all the rows.
// Values in the array are matched sequentially to the columns,
// based on the order in which they appear in the table.
object[][] rows =
[
[1, "O0001", "Mountain Bike", 1419.5, 36],
[2, "O0001", "Road Bike", 1233.6, 16],
[3, "O0001", "Touring Bike", 1653.3, 32],
[4, "O0002", "Mountain Bike", 1419.5, 24],
[5, "O0002", "Road Bike", 1233.6, 12],
[6, "O0003", "Mountain Bike", 1419.5, 48],
[7, "O0003", "Touring Bike", 1653.3, 8],
];
foreach (object[] row in rows)
{
orderDetailTable.Rows.Add(row);
}
}
private static void ShowTable(DataTable table)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("{0,-14}", col.ColumnName);
}
Console.WriteLine();
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
if (col.DataType.Equals(typeof(DateTime)))
Console.Write("{0,-14:d}", row[col]);
else if (col.DataType.Equals(typeof(decimal)))
Console.Write("{0,-14:C}", row[col]);
else
Console.Write("{0,-14}", row[col]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}
' Put the next line into the Declarations section.
private dataSet As DataSet
Private Sub MakeDataTables()
' Run all of the functions.
MakeParentTable()
MakeChildTable()
MakeDataRelation()
BindToDataGrid()
End Sub
Private Sub MakeParentTable()
' Create a new DataTable.
Dim table As New DataTable("ParentTable")
' Declare variables for DataColumn and DataRow objects.
Dim column As DataColumn
Dim row As DataRow
' Create new DataColumn, set DataType, ColumnName
' and add to DataTable.
column = New DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = "id"
column.ReadOnly = True
column.Unique = True
' Add the Column to the DataColumnCollection.
table.Columns.Add(column)
' Create second column.
column = New DataColumn()
column.DataType = System.Type.GetType("System.String")
column.ColumnName = "ParentItem"
column.AutoIncrement = False
column.Caption = "ParentItem"
column.ReadOnly = False
column.Unique = False
' Add the column to the table.
table.Columns.Add(column)
' Make the ID column the primary key column.
Dim PrimaryKeyColumns(0) As DataColumn
PrimaryKeyColumns(0)= table.Columns("id")
table.PrimaryKey = PrimaryKeyColumns
' Instantiate the DataSet variable.
dataSet = New DataSet()
' Add the new DataTable to the DataSet.
dataSet.Tables.Add(table)
' Create three new DataRow objects and add
' them to the DataTable
Dim i As Integer
For i = 0 to 2
row = table.NewRow()
row("id") = i
row("ParentItem") = "ParentItem " + i.ToString()
table.Rows.Add(row)
Next i
End Sub
Private Sub MakeChildTable()
' Create a new DataTable.
Dim table As New DataTable("childTable")
Dim column As DataColumn
Dim row As DataRow
' Create first column and add to the DataTable.
column = New DataColumn()
column.DataType= System.Type.GetType("System.Int32")
column.ColumnName = "ChildID"
column.AutoIncrement = True
column.Caption = "ID"
column.ReadOnly = True
column.Unique = True
' Add the column to the DataColumnCollection.
table.Columns.Add(column)
' Create second column.
column = New DataColumn()
column.DataType= System.Type.GetType("System.String")
column.ColumnName = "ChildItem"
column.AutoIncrement = False
column.Caption = "ChildItem"
column.ReadOnly = False
column.Unique = False
table.Columns.Add(column)
' Create third column.
column = New DataColumn()
column.DataType= System.Type.GetType("System.Int32")
column.ColumnName = "ParentID"
column.AutoIncrement = False
column.Caption = "ParentID"
column.ReadOnly = False
column.Unique = False
table.Columns.Add(column)
dataSet.Tables.Add(table)
' Create three sets of DataRow objects, five rows each,
' and add to DataTable.
Dim i As Integer
For i = 0 to 4
row = table.NewRow()
row("childID") = i
row("ChildItem") = "Item " + i.ToString()
row("ParentID") = 0
table.Rows.Add(row)
Next i
For i = 0 to 4
row = table.NewRow()
row("childID") = i + 5
row("ChildItem") = "Item " + i.ToString()
row("ParentID") = 1
table.Rows.Add(row)
Next i
For i = 0 to 4
row = table.NewRow()
row("childID") = i + 10
row("ChildItem") = "Item " + i.ToString()
row("ParentID") = 2
table.Rows.Add(row)
Next i
End Sub
Private Sub MakeDataRelation()
' DataRelation requires two DataColumn
' (parent and child) and a name.
Dim parentColumn As DataColumn = _
dataSet.Tables("ParentTable").Columns("id")
Dim childColumn As DataColumn = _
dataSet.Tables("ChildTable").Columns("ParentID")
Dim relation As DataRelation = new _
DataRelation("parent2Child", parentColumn, childColumn)
dataSet.Tables("ChildTable").ParentRelations.Add(relation)
End Sub
Private Sub BindToDataGrid()
' Instruct the DataGrid to bind to the DataSet, with the
' ParentTable as the topmost DataTable.
DataGrid1.SetDataBinding(dataSet,"ParentTable")
End Sub
備註
類別 DataTable 是 ADO.NET 連結庫中的中央物件。 使用 DataTable 其他物件包括 DataSet 與 DataView。
DataTable 物件名稱具有條件式的大小寫區分。 例如,如果其中一個 DataTable 名稱為 「mydatatable」,而另一個名為 「Mydatatable」,則用來搜尋其中一個數據表的字串會被視為區分大小寫。 不過,如果 「mydatatable」 存在且 「Mydatatable」 不存在,則搜尋字串會視為不區分大小寫。 DataSet可以包含兩個DataTable具有相同TableName屬性值但不同Namespace屬性值的物件。 如需使用 DataTable 對象的詳細資訊,請參閱 建立DataTable。
如果您要以程式設計方式建立 DataTable ,您必須先將 物件新增 DataColumn 至 DataColumnCollection (透過 Columns 屬性存取) 來定義其架構。 如需新增 DataColumn 對象的詳細資訊,請參閱 將數據行加入DataTable。
若要將資料列加入 至 DataTable,您必須先使用 NewRow 方法傳回新的 DataRow 物件。 方法 NewRow 傳回具有DataTable架構的列,因其是由表的DataColumnCollection所定義。 可以儲存的數據列 DataTable 數目上限為 16,777,216。 如需詳細資訊,請參閱 將數據新增至 DataTable。
DataTable也包含物件的集合Constraint,可用來確保數據的完整性。 如需詳細資訊,請參閱 DataTable 條件約束。
有許多 DataTable 事件可用來判斷數據表何時進行變更。 這些包括 RowChanged、 RowChanging、 RowDeleting和 RowDeleted。 如需可以搭配 DataTable使用之事件的詳細資訊,請參閱 處理 DataTable 事件。
建立 的實例 DataTable 時,某些讀取/寫入屬性會設定為初始值。 如需這些值的清單,請參閱建構函式 DataTable 。
Note
DataSet 和 DataTable 物件繼承自 MarshalByValueComponent,並支援 ISerializable .NET 遠端處理介面。 這些是唯一可用於 .NET 遠端處理的 ADO.NET 物件。
安全性考慮
如需 DataSet 和 DataTable 安全性的相關信息,請參閱 安全性指引。
建構函式
| 名稱 | Description |
|---|---|
| DataTable() |
初始化一個無參數的新類別實例 DataTable 。 |
| DataTable(SerializationInfo, StreamingContext) |
已淘汰.
初始化一個新的類別實例 DataTable ,並使用序列化資料。 |
| DataTable(String, String) |
使用指定的資料表名稱與命名空間初始化該類別的新實例 DataTable 。 |
| DataTable(String) |
初始化一個以指定資料表名稱的新 DataTable 類別實例。 |
欄位
| 名稱 | Description |
|---|---|
| fInitInProgress |
檢查初始化是否正在進行中。 初始化發生在執行時。 |
屬性
| 名稱 | Description |
|---|---|
| CaseSensitive |
表示表中字串比較是否區分大小寫。 |
| ChildRelations |
為此 DataTable收集兒童關係。 |
| Columns |
取得屬於此表的欄位集合。 |
| Constraints |
取得由此表維持的約束集合。 |
| Container |
取得元件的容器。 (繼承來源 MarshalByValueComponent) |
| DataSet |
這 DataSet 張桌子該屬於什麼。 |
| DefaultView |
會獲得自訂的表格視圖,可能包含過濾檢視或游標位置。 |
| DesignMode |
會取得一個值,表示該元件目前是否處於設計模式。 (繼承來源 MarshalByValueComponent) |
| DisplayExpression |
取得或設定一個表達式,回傳用來在使用者介面中表示此表格的值。 這個 |
| Events |
取得與此元件相連的事件處理程序清單。 (繼承來源 MarshalByValueComponent) |
| ExtendedProperties |
取得自訂用戶資訊的集合。 |
| HasErrors |
會得到一個值,表示該資料表所屬的任一資料表 DataSet 中是否有錯誤。 |
| IsInitialized |
會得到一個表示是否 DataTable 已初始化的值。 |
| Locale |
取得或設定用於比較表格中字串的地點資訊。 |
| MinimumCapacity |
取得或設定此表的初始大小。 |
| Namespace |
取得或設定儲存在 DataTable. 中資料的 XML 表示名稱空間。 |
| ParentRelations |
取得父 DataTable關係的集合。 |
| Prefix |
取得或設定儲存在 DataTable. 中資料的 XML 表示名稱空間。 |
| PrimaryKey |
取得或設定一個欄位陣列,作為資料表的主鍵。 |
| RemotingFormat |
取得或設定序列化格式。 |
| Rows |
取得屬於此表的列集合。 |
| Site | |
| TableName |
取得或設定 的名稱。DataTable |
方法
事件
| 名稱 | Description |
|---|---|
| ColumnChanged |
發生在 中指定DataColumnDataRow值被更改後。 |
| ColumnChanging |
當值在 中被更改為指定的DataColumnDataRow值時,會發生。 |
| Disposed |
新增一個事件處理器來監聽元件上的事件。Disposed (繼承來源 MarshalByValueComponent) |
| Initialized |
發生在初始 DataTable 化之後。 |
| RowChanged |
發生在 a DataRow 成功更改之後。 |
| RowChanging |
當 a DataRow 正在改變時會發生。 |
| RowDeleted |
發生在資料表中某一列被刪除之後。 |
| RowDeleting |
發生在資料表中某一列即將被刪除之前。 |
| TableCleared |
在A DataTable 被清除後發生。 |
| TableClearing |
當 a DataTable 被清除時發生。 |
| TableNewRow |
當新插入 DataRow 時會發生。 |
明確介面實作
| 名稱 | Description |
|---|---|
| IListSource.ContainsListCollection |
關於此成員的描述,請參見 ContainsListCollection。 |
| IListSource.GetList() |
關於此成員的描述,請參見 GetList()。 |
| ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
填充序列化資訊物件所需的資料。DataTable |
| IXmlSerializable.GetSchema() |
關於此成員的描述,請參見 GetSchema()。 |
| IXmlSerializable.ReadXml(XmlReader) |
關於此成員的描述,請參見 ReadXml(XmlReader)。 |
| IXmlSerializable.WriteXml(XmlWriter) |
關於此成員的描述,請參見 WriteXml(XmlWriter)。 |
擴充方法
適用於
執行緒安全性
此類型適合多執行緒讀取操作。 您必須同步處理任何寫入作業。