DataTable Класс
Определение
Представляет одну таблицу данных в памяти.Represents one table of in-memory data.
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
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
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
[<System.Serializable>]
type DataTable = class
inherit MarshalByValueComponent
interface IListSource
interface ISupportInitializeNotification
interface ISerializable
interface IXmlSerializable
interface ISupportInitialize
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 и один DataRelation объект, а затем добавляются новые объекты в DataSet .The following example creates two DataTable objects and one DataRelation object, and adds the new objects to a DataSet. Таблицы затем отображаются в DataGridView элементе управления.The tables are then displayed in a DataGridView control.
// Put the next line into the Declarations section.
private System.Data.DataSet dataSet;
private void MakeDataTables()
{
// Run all of the functions.
MakeParentTable();
MakeChildTable();
MakeDataRelation();
BindToDataGrid();
}
private void MakeParentTable()
{
// Create a new DataTable.
System.Data.DataTable table = new DataTable("ParentTable");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// 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.
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
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
for (int i = 0; i<= 2; i++)
{
row = table.NewRow();
row["id"] = i;
row["ParentItem"] = "ParentItem " + i;
table.Rows.Add(row);
}
}
private void MakeChildTable()
{
// Create a new DataTable.
DataTable table = new DataTable("childTable");
DataColumn column;
DataRow row;
// 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.
for(int i = 0; i <= 4; i ++)
{
row = table.NewRow();
row["childID"] = i;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 0 ;
table.Rows.Add(row);
}
for(int i = 0; i <= 4; i ++)
{
row = table.NewRow();
row["childID"] = i + 5;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 1 ;
table.Rows.Add(row);
}
for(int i = 0; i <= 4; i ++)
{
row = table.NewRow();
row["childID"] = i + 10;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 2 ;
table.Rows.Add(row);
}
}
private void MakeDataRelation()
{
// DataRelation requires two DataColumn
// (parent and child) and a name.
DataColumn parentColumn =
dataSet.Tables["ParentTable"].Columns["id"];
DataColumn childColumn =
dataSet.Tables["ChildTable"].Columns["ParentID"];
DataRelation relation = new
DataRelation("parent2Child", parentColumn, childColumn);
dataSet.Tables["ChildTable"].ParentRelations.Add(relation);
}
private void BindToDataGrid()
{
// Instruct the DataGrid to bind to the DataSet, with the
// ParentTable as the topmost DataTable.
dataGrid1.SetDataBinding(dataSet,"ParentTable");
}
' 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
В этом примере показано, как создать таблицу данных вручную с конкретными определениями схемы:This sample demonstrates how to create a DataTable manually with specific schema definitions:
Создайте несколько таблиц DataTable и определите начальные столбцы.Create multiple DataTables and define the initial columns.
Создайте ограничения таблицы.Create the table constraints.
Вставьте значения и отобразите таблицы.Insert the values and display the tables.
Создайте столбцы выражений и отобразите таблицы.Create the expression columns and display the tables.
Проекты C# и Visual Basic с этим примером кода можно найти в примерах кода для разработчиков.C# and Visual Basic projects with this code sample can be found on Developer Code Samples.
using System;
using System.Data;
class Program {
static void Main(string[] args) {
// Create two tables and add them into the DataSet
DataTable orderTable = CreateOrderTable();
DataTable orderDetailTable = CreateOrderDetailTable();
DataSet salesSet = new DataSet();
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 constriant, you will see the following error if inserting order detail with the wrong OrderId: ");
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 DataColumn("SubTotal", typeof(Decimal), "Sum(Child.LineTotal)");
orderTable.Columns.Add(colSub);
// Compute the tax by referencing the SubTotal expression column.
DataColumn colTax = new DataColumn("Tax", typeof(Decimal), "SubTotal*0.1");
orderTable.Columns.Add(colTax);
// If the OrderId is 'Total', compute the due on all orders; or compute the due on this order.
DataColumn colTotal = new DataColumn("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 DataTable("Order");
// Define one column.
DataColumn colId = new DataColumn("OrderId", typeof(String));
orderTable.Columns.Add(colId);
DataColumn colDate = new DataColumn("OrderDate", typeof(DateTime));
orderTable.Columns.Add(colDate);
// Set the OrderId column as the primary key.
orderTable.PrimaryKey = new DataColumn[] { colId };
return orderTable;
}
private static DataTable CreateOrderDetailTable() {
DataTable orderDetailTable = new DataTable("OrderDetail");
// Define all the columns once.
DataColumn[] cols ={
new DataColumn("OrderDetailId",typeof(Int32)),
new DataColumn("OrderId",typeof(String)),
new DataColumn("Product",typeof(String)),
new DataColumn("UnitPrice",typeof(Decimal)),
new DataColumn("OrderQty",typeof(Int32)),
new DataColumn("LineTotal",typeof(Decimal),"UnitPrice*OrderQty")
};
orderDetailTable.Columns.AddRange(cols);
orderDetailTable.PrimaryKey = new DataColumn[] { orderDetailTable.Columns["OrderDetailId"] };
return orderDetailTable;
}
private static void InsertOrders(DataTable orderTable) {
// Add one row once.
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 = {
new Object[]{1,"O0001","Mountain Bike",1419.5,36},
new Object[]{2,"O0001","Road Bike",1233.6,16},
new Object[]{3,"O0001","Touring Bike",1653.3,32},
new Object[]{4,"O0002","Mountain Bike",1419.5,24},
new Object[]{5,"O0002","Road Bike",1233.6,12},
new Object[]{6,"O0003","Mountain Bike",1419.5,48},
new Object[]{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();
}
}
Imports System.Data
Class Program
Public Shared Sub Main(args As String())
' Create two tables and add them into the DataSet
Dim orderTable As DataTable = CreateOrderTable()
Dim orderDetailTable As DataTable = CreateOrderDetailTable()
Dim salesSet As New DataSet()
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 constriant, you will see the following error if inserting order detail with the wrong OrderId: ")
Try
Dim errorRow As DataRow = orderDetailTable.NewRow()
errorRow(0) = 1
errorRow(1) = "O0007"
orderDetailTable.Rows.Add(errorRow)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
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.
Dim colSub As New DataColumn("SubTotal", GetType([Decimal]), "Sum(Child.LineTotal)")
orderTable.Columns.Add(colSub)
' Compute the tax by referencing the SubTotal expression column.
Dim colTax As New DataColumn("Tax", GetType([Decimal]), "SubTotal*0.1")
orderTable.Columns.Add(colTax)
' If the OrderId is 'Total', compute the due on all orders; or compute the due on this order.
Dim colTotal As New DataColumn("TotalDue", GetType([Decimal]), "IIF(OrderId='Total',Sum(SubTotal)+Sum(Tax),SubTotal+Tax)")
orderTable.Columns.Add(colTotal)
Dim row As DataRow = 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()
End Sub
Private Shared Function CreateOrderTable() As DataTable
Dim orderTable As New DataTable("Order")
' Define one column.
Dim colId As New DataColumn("OrderId", GetType([String]))
orderTable.Columns.Add(colId)
Dim colDate As New DataColumn("OrderDate", GetType(DateTime))
orderTable.Columns.Add(colDate)
' Set the OrderId column as the primary key.
orderTable.PrimaryKey = New DataColumn() {colId}
Return orderTable
End Function
Private Shared Function CreateOrderDetailTable() As DataTable
Dim orderDetailTable As New DataTable("OrderDetail")
' Define all the columns once.
Dim cols As DataColumn() = {New DataColumn("OrderDetailId", GetType(Int32)), New DataColumn("OrderId", GetType([String])), New DataColumn("Product", GetType([String])), New DataColumn("UnitPrice", GetType([Decimal])), New DataColumn("OrderQty", GetType(Int32)), New DataColumn("LineTotal", GetType([Decimal]), "UnitPrice*OrderQty")}
orderDetailTable.Columns.AddRange(cols)
orderDetailTable.PrimaryKey = New DataColumn() {orderDetailTable.Columns("OrderDetailId")}
Return orderDetailTable
End Function
Private Shared Sub InsertOrders(orderTable As DataTable)
' Add one row once.
Dim row1 As DataRow = orderTable.NewRow()
row1("OrderId") = "O0001"
row1("OrderDate") = New DateTime(2013, 3, 1)
orderTable.Rows.Add(row1)
Dim row2 As DataRow = orderTable.NewRow()
row2("OrderId") = "O0002"
row2("OrderDate") = New DateTime(2013, 3, 12)
orderTable.Rows.Add(row2)
Dim row3 As DataRow = orderTable.NewRow()
row3("OrderId") = "O0003"
row3("OrderDate") = New DateTime(2013, 3, 20)
orderTable.Rows.Add(row3)
End Sub
Private Shared Sub InsertOrderDetails(orderDetailTable As DataTable)
' 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.
Dim rows As [Object]() = {New [Object]() {1, "O0001", "Mountain Bike", 1419.5, 36}, New [Object]() {2, "O0001", "Road Bike", 1233.6, 16}, New [Object]() {3, "O0001", "Touring Bike", 1653.3, 32}, New [Object]() {4, "O0002", "Mountain Bike", 1419.5, 24}, New [Object]() {5, "O0002", "Road Bike", 1233.6, 12}, New [Object]() {6, "O0003", "Mountain Bike", 1419.5, 48}, _
New [Object]() {7, "O0003", "Touring Bike", 1653.3, 8}}
For Each row As [Object]() In rows
orderDetailTable.Rows.Add(row)
Next
End Sub
Private Shared Sub ShowTable(table As DataTable)
For Each col As DataColumn In table.Columns
Console.Write("{0,-14}", col.ColumnName)
Next
Console.WriteLine()
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
If col.DataType.Equals(GetType(DateTime)) Then
Console.Write("{0,-14:d}", row(col))
ElseIf col.DataType.Equals(GetType([Decimal])) Then
Console.Write("{0,-14:C}", row(col))
Else
Console.Write("{0,-14}", row(col))
End If
Next
Console.WriteLine()
Next
Console.WriteLine()
End Sub
End Class
Комментарии
DataTableЯвляется центральным объектом в библиотеке ADO.NET.The DataTable is a central object in the ADO.NET library. Другие объекты, использующие, DataTable включают DataSet и DataView .Other objects that use the DataTable include the DataSet and the DataView.
При доступе к DataTable объектам Обратите внимание, что они чувствительны к регистру.When accessing DataTable objects, note that they are conditionally case sensitive. Например, если один DataTable из них имеет имя «Mydatatable», а другой — «Mydatatable», то строка, используемая для поиска одной из таблиц, считается с учетом регистра.For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. Однако если "Mydatatable" существует, а "Mydatatable" — нет, то строка поиска считается нечувствительной к регистру.However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. DataSetМожет содержать два DataTable объекта с одинаковым TableName значением свойства, но разными Namespace значениями свойств.A DataSet can contain two DataTable objects that have the same TableName property value but different Namespace property values. Дополнительные сведения о работе с DataTable объектами см. в разделе Создание таблицыданных.For more information about working with DataTable objects, see Creating a DataTable.
Если вы создаете DataTable программно, необходимо сначала определить его схему, добавив DataColumn объекты в объект DataColumnCollection (доступ к которому осуществляется через Columns свойство).If you are creating a DataTable programmatically, you must first define its schema by adding DataColumn objects to the DataColumnCollection (accessed through the Columns property). Дополнительные сведения о добавлении DataColumn объектов см. в разделе Добавление столбцов в таблицуданных.For more information about adding DataColumn objects, see Adding Columns to a DataTable.
Чтобы добавить строки в DataTable , необходимо сначала использовать NewRow метод для возврата нового DataRow объекта.To add rows to a DataTable, you must first use the NewRow method to return a new DataRow object. NewRowМетод возвращает строку со схемой DataTable , так как она определена в таблице DataColumnCollection .The NewRow method returns a row with the schema of the DataTable, as it is defined by the table's DataColumnCollection. Максимальное число строк, которое DataTable может храниться в, — 16 777 216.The maximum number of rows that a DataTable can store is 16,777,216. Дополнительные сведения см. в разделе Добавление данных в таблицу DataTable.For more information, see Adding Data to a DataTable.
Объект DataTable также содержит коллекцию Constraint объектов, которые можно использовать для обеспечения целостности данных.The DataTable also contains a collection of Constraint objects that can be used to ensure the integrity of the data. Дополнительные сведения см. в разделе ограничения DataTable.For more information, see DataTable Constraints.
Существует много DataTable событий, которые можно использовать для определения времени внесения изменений в таблицу.There are many DataTable events that can be used to determine when changes are made to a table. К ним относятся RowChanged, RowChanging, RowDeleting и RowDeleted.These include RowChanged, RowChanging, RowDeleting, and RowDeleted. Дополнительные сведения о событиях, которые можно использовать с DataTable , см. в разделе Обработка событий DataTable.For more information about the events that can be used with a DataTable, see Handling DataTable Events.
При DataTable создании экземпляра для некоторых свойств чтения и записи задаются начальные значения.When an instance of DataTable is created, some of the read/write properties are set to initial values. Список этих значений см DataTable.DataTable . в разделе конструктора.For a list of these values, see the DataTable.DataTable constructor topic.
Примечание
DataSetОбъекты и DataTable наследуются от MarshalByValueComponent и поддерживают ISerializable интерфейс для .NET Framework удаленного взаимодействия.The DataSet and DataTable objects inherit from MarshalByValueComponent and support the ISerializable interface for .NET Framework remoting. Это единственные объекты ADO.NET, которые можно использовать для удаленного взаимодействия .NET Framework.These are the only ADO.NET objects that you can use for .NET Framework remoting.
Вопросы безопасностиSecurity considerations
Сведения о наборах данных и безопасности DataTable см. в руководстве по безопасности.For information about DataSet and DataTable security, see Security guidance.
Конструкторы
DataTable() |
Инициализирует новый экземпляр класса DataTable, не передавая ему никаких аргументов.Initializes a new instance of the DataTable class with no arguments. |
DataTable(SerializationInfo, StreamingContext) |
Инициализирует новый экземпляр класса DataTable со свойствами SerializationInfo и StreamingContext.Initializes a new instance of the DataTable class with the SerializationInfo and the StreamingContext. |
DataTable(String) |
Инициализирует новый экземпляр класса DataTable с указанным именем таблицы.Initializes a new instance of the DataTable class with the specified table name. |
DataTable(String, String) |
Инициализирует новый экземпляр класса DataTable с заданными именем таблицы и пространством имен.Initializes a new instance of the DataTable class using the specified table name and namespace. |
Поля
fInitInProgress |
Проверяет, выполняется ли инициализация.Checks whether initialization is in progress. Инициализация происходит во время выполнения.The initialization occurs at run time. |
Свойства
CaseSensitive |
Показывает, учитывается ли регистр при сравнении строк в таблице.Indicates whether string comparisons within the table are case-sensitive. |
ChildRelations |
Получает коллекцию дочерних отношений для объекта DataTable.Gets the collection of child relations for this DataTable. |
Columns |
Получает коллекцию столбцов, принадлежащих данной таблице.Gets the collection of columns that belong to this table. |
Constraints |
Получает коллекцию ограничений, содержащихся в данной таблице.Gets the collection of constraints maintained by this table. |
Container |
Возвращает контейнер для компонента.Gets the container for the component. (Унаследовано от MarshalByValueComponent) |
DataSet |
Получает класс DataSet, к которому принадлежит данная таблица.Gets the DataSet to which this table belongs. |
DefaultView |
Получает настраиваемое представление таблицы, которая может включать в себя представление с фильтром или положение курсора.Gets a customized view of the table that may include a filtered view, or a cursor position. |
DesignMode |
Возвращает значение, показывающее, находится ли компонент в настоящий момент в режиме разработки.Gets a value indicating whether the component is currently in design mode. (Унаследовано от MarshalByValueComponent) |
DisplayExpression |
Возвращает или задает выражение, возвращающее значение, используемое для представления таблицы в пользовательском интерфейсе.Gets or sets the expression that returns a value used to represent this table in the user interface. Свойство |
Events |
Возвращает список обработчиков событий, которые прикреплены к этому компоненту.Gets the list of event handlers that are attached to this component. (Унаследовано от MarshalByValueComponent) |
ExtendedProperties |
Получает коллекцию настраиваемых пользовательских сведений.Gets the collection of customized user information. |
HasErrors |
Получает значение, указывающее наличие ошибок в строках таблиц класса DataSet, к которому принадлежат таблицы.Gets a value indicating whether there are errors in any of the rows in any of the tables of the DataSet to which the table belongs. |
IsInitialized |
Получает значение, указывающее, инициализирована ли таблица DataTable.Gets a value that indicates whether the DataTable is initialized. |
Locale |
Возвращает или задает сведения о языке, используемые для сравнения строк таблицы.Gets or sets the locale information used to compare strings within the table. |
MinimumCapacity |
Возвращает или задает начальный размер таблицы.Gets or sets the initial starting size for this table. |
Namespace |
Возвращает или задает пространство имен для представления данных объекта DataTable в формате XML.Gets or sets the namespace for the XML representation of the data stored in the DataTable. |
ParentRelations |
Получает коллекцию родительских отношений для объекта DataTable.Gets the collection of parent relations for this DataTable. |
Prefix |
Возвращает или задает пространство имен для представления данных объекта DataTable в формате XML.Gets or sets the namespace for the XML representation of the data stored in the DataTable. |
PrimaryKey |
Возвращает или задает массив столбцов, которые являются столбцами первичного ключа для таблицы данных.Gets or sets an array of columns that function as primary keys for the data table. |
RemotingFormat |
Возвращает или задает формат сериализации.Gets or sets the serialization format. |
Rows |
Получает коллекцию строк, принадлежащих данной таблице.Gets the collection of rows that belong to this table. |
Site |
Возвращает или задает тип ISite для объекта DataTable.Gets or sets an ISite for the DataTable. |
TableName |
Возвращает или задает имя таблицы для объекта DataTable.Gets or sets the name of the DataTable. |
Методы
AcceptChanges() |
Фиксирует все изменения, внесенные в таблицу после последнего вызова метода AcceptChanges().Commits all the changes made to this table since the last time AcceptChanges() was called. |
BeginInit() |
Начинает инициализацию DataTable, используемого в форме или другим компонентом.Begins the initialization of a DataTable that is used on a form or used by another component. Инициализация происходит во время выполнения.The initialization occurs at run time. |
BeginLoadData() |
Отключает уведомления, ведение индексов и ограничения в процессе загрузки данных.Turns off notifications, index maintenance, and constraints while loading data. |
Clear() |
Очищает DataTable от всех данных.Clears the DataTable of all data. |
Clone() |
Копирует структуру объекта DataTable, включая все схемы и ограничения DataTable.Clones the structure of the DataTable, including all DataTable schemas and constraints. |
Compute(String, String) |
Вычисляет заданное выражение для текущих строк, отвечающих условию фильтра.Computes the given expression on the current rows that pass the filter criteria. |
Copy() |
Копирует структуру и данные для DataTable.Copies both the structure and data for this DataTable. |
CreateDataReader() |
Возвращает объект DataTableReader, соответствующий данным в этой таблице DataTable.Returns a DataTableReader corresponding to the data within this DataTable. |
CreateInstance() |
Создает новый экземпляр DataTable.Creates a new instance of DataTable. |
Dispose() |
Освобождает все ресурсы, занятые модулем MarshalByValueComponent.Releases all resources used by the MarshalByValueComponent. (Унаследовано от MarshalByValueComponent) |
Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые объектом MarshalByValueComponent, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the MarshalByValueComponent and optionally releases the managed resources. (Унаследовано от MarshalByValueComponent) |
EndInit() |
Завершает инициализацию DataTable, используемого в форме или другим компонентом.Ends the initialization of a DataTable that is used on a form or used by another component. Инициализация происходит во время выполнения.The initialization occurs at run time. |
EndLoadData() |
Включает уведомления, ведение индексов и ограничения после загрузки данных.Turns on notifications, index maintenance, and constraints after loading data. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetChanges() |
Получает копию таблицы DataTable, содержащую все изменения, внесенные после ее загрузки или после последнего вызова метода AcceptChanges().Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges() was last called. |
GetChanges(DataRowState) |
Получает копию таблицы DataTable, содержащую все изменения, внесенные после ее последней загрузки или после вызова метода AcceptChanges() и отфильтрованные по параметру DataRowState.Gets a copy of the DataTable containing all changes made to it since it was last loaded, or since AcceptChanges() was called, filtered by DataRowState. |
GetDataTableSchema(XmlSchemaSet) |
Этот метод возвращает экземпляр XmlSchemaSet, содержащий язык описания веб-служб (WSDL), который описывает объект DataTable для веб-служб.This method returns an XmlSchemaSet instance containing the Web Services Description Language (WSDL) that describes the DataTable for Web Services. |
GetErrors() |
Получает массив объектов DataRow, содержащих ошибки.Gets an array of DataRow objects that contain errors. |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Заполняет объект сведений о сериализации данными, необходимыми для сериализации DataTable.Populates a serialization information object with the data needed to serialize the DataTable. |
GetRowType() |
Получает тип строки.Gets the row type. |
GetSchema() |
Описание этого члена см. в разделе GetSchema().For a description of this member, see GetSchema(). |
GetService(Type) |
Возвращает средство реализации объекта IServiceProvider.Gets the implementer of the IServiceProvider. (Унаследовано от MarshalByValueComponent) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
ImportRow(DataRow) |
Копирует объект DataRow в DataTable, сохраняя все параметры свойств, а также текущие и исходные значения.Copies a DataRow into a DataTable, preserving any property settings, as well as original and current values. |
Load(IDataReader) |
Заполняет таблицу DataTable значениями из источника данных с помощью предоставляемого объекта IDataReader.Fills a DataTable with values from a data source using the supplied IDataReader. Если объект DataTable уже содержит строки, входящие данные из источника данных объединяются с существующими строками.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows. |
Load(IDataReader, LoadOption) |
Заполняет таблицу DataTable значениями из источника данных с помощью предоставляемого объекта IDataReader.Fills a DataTable with values from a data source using the supplied IDataReader. Если объект |
Load(IDataReader, LoadOption, FillErrorEventHandler) |
Заполняет таблицу DataTable значениями из источника данных с помощью предоставляемого объекта IDataReader, использующего делегат для обработки ошибок.Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate. |
LoadDataRow(Object[], Boolean) |
Находит и обновляет конкретную строку.Finds and updates a specific row. Если нужная строка не найдена, то с помощью заданных значений создается новая строка.If no matching row is found, a new row is created using the given values. |
LoadDataRow(Object[], LoadOption) |
Находит и обновляет конкретную строку.Finds and updates a specific row. Если нужная строка не найдена, то с помощью заданных значений создается новая строка.If no matching row is found, a new row is created using the given values. |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
Merge(DataTable) |
Объединяет заданный объект DataTable с текущим объектом DataTable.Merge the specified DataTable with the current DataTable. |
Merge(DataTable, Boolean) |
Объедините заданный объект DataTable с текущим объектом |
Merge(DataTable, Boolean, MissingSchemaAction) |
Объедините заданный объект DataTable с текущим объектом |
NewRow() |
Создает новый класс DataRow, имеющий ту же схему, что и таблица.Creates a new DataRow with the same schema as the table. |
NewRowArray(Int32) | |
NewRowFromBuilder(DataRowBuilder) |
Создает новую строку из существующей строки.Creates a new row from an existing row. |
OnColumnChanged(DataColumnChangeEventArgs) |
Вызывает событие ColumnChanged.Raises the ColumnChanged event. |
OnColumnChanging(DataColumnChangeEventArgs) |
Вызывает событие ColumnChanging.Raises the ColumnChanging event. |
OnPropertyChanging(PropertyChangedEventArgs) |
Вызывает событие PropertyChanged.Raises the PropertyChanged event. |
OnRemoveColumn(DataColumn) |
Сообщает классу DataTable об удалении объекта DataColumn.Notifies the DataTable that a DataColumn is being removed. |
OnRowChanged(DataRowChangeEventArgs) |
Вызывает событие RowChanged.Raises the RowChanged event. |
OnRowChanging(DataRowChangeEventArgs) |
Вызывает событие RowChanging.Raises the RowChanging event. |
OnRowDeleted(DataRowChangeEventArgs) |
Вызывает событие RowDeleted.Raises the RowDeleted event. |
OnRowDeleting(DataRowChangeEventArgs) |
Вызывает событие RowDeleting.Raises the RowDeleting event. |
OnTableCleared(DataTableClearEventArgs) |
Вызывает событие TableCleared.Raises the TableCleared event. |
OnTableClearing(DataTableClearEventArgs) |
Вызывает событие TableClearing.Raises the TableClearing event. |
OnTableNewRow(DataTableNewRowEventArgs) |
Вызывает событие TableNewRow.Raises the TableNewRow event. |
ReadXml(Stream) |
Считывает XML-схему и данные в DataTable, используя указанный класс Stream.Reads XML schema and data into the DataTable using the specified Stream. |
ReadXml(String) |
Читает данные и схему XML в DataTable из указанного файла.Reads XML schema and data into the DataTable from the specified file. |
ReadXml(TextReader) |
Считывает XML-схему и данные в DataTable, используя указанный класс TextReader.Reads XML schema and data into the DataTable using the specified TextReader. |
ReadXml(XmlReader) |
Читает данные и схему XML в DataTable, используя указанное средство чтения XmlReader.Reads XML Schema and Data into the DataTable using the specified XmlReader. |
ReadXmlSchema(Stream) |
Считывает XML-схему в DataTable, используя указанный поток.Reads an XML schema into the DataTable using the specified stream. |
ReadXmlSchema(String) |
Считывает XML-схему из указанного файла в таблицу DataTable.Reads an XML schema into the DataTable from the specified file. |
ReadXmlSchema(TextReader) |
Считывает XML-схему в DataTable, используя указанный объект TextReader.Reads an XML schema into the DataTable using the specified TextReader. |
ReadXmlSchema(XmlReader) |
Считывает XML-схему в DataTable, используя указанный объект XmlReader.Reads an XML schema into the DataTable using the specified XmlReader. |
ReadXmlSerializable(XmlReader) |
Считывает из XML-потока.Reads from an XML stream. |
RejectChanges() |
Выполняется откат всех изменений, внесенных в таблицу с момента ее загрузки или после последнего вызова метода AcceptChanges().Rolls back all changes that have been made to the table since it was loaded, or the last time AcceptChanges() was called. |
Reset() |
Возвращает объект DataTable в исходное состояние.Resets the DataTable to its original state. Сброс удаляет все данные, индексы, связи и столбцы таблицы.Reset removes all data, indexes, relations, and columns of the table. Если набор данных содержит таблицы данных, то таблица по-прежнему будет частью набора данных после того, как таблица будет сброшена.If a DataSet includes a DataTable, the table will still be part of the DataSet after the table is reset. |
Select() |
Получает массив всех объектов DataRow.Gets an array of all DataRow objects. |
Select(String) |
Получает массив всех объектов DataRow, отвечающих условиям фильтра.Gets an array of all DataRow objects that match the filter criteria. |
Select(String, String) |
Получает массив всех объектов DataRow, отвечающих условиям фильтра, согласно указанному порядку сортировки.Gets an array of all DataRow objects that match the filter criteria, in the specified sort order. |
Select(String, String, DataViewRowState) |
Получает массив всех объектов DataRow, отвечающих условиям фильтра, согласно порядку сортировки, соответствующему указанному состоянию.Gets an array of all DataRow objects that match the filter in the order of the sort that match the specified state. |
ToString() |
Получает свойства TableName и DisplayExpression, если существует сцепленная строка.Gets the TableName and DisplayExpression, if there is one as a concatenated string. |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |
WriteXml(Stream) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента Stream.Writes the current contents of the DataTable as XML using the specified Stream. |
WriteXml(Stream, Boolean) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента Stream.Writes the current contents of the DataTable as XML using the specified Stream. Чтобы сохранить данные для таблицы и всех ее потомков, установите для параметра |
WriteXml(Stream, XmlWriteMode) |
Записывает текущие данные и по возможности схему для DataTable в указанный файл с помощью заданного объекта XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable to the specified file using the specified XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(Stream, XmlWriteMode, Boolean) |
Записывает текущие данные и по возможности схему для DataTable в указанный файл с помощью заданного объекта XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable to the specified file using the specified XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(String) |
Записывает текущее содержимое таблицы DataTable в формате XML, используя указанный файл.Writes the current contents of the DataTable as XML using the specified file. |
WriteXml(String, Boolean) |
Записывает текущее содержимое таблицы DataTable в формате XML, используя указанный файл.Writes the current contents of the DataTable as XML using the specified file. Чтобы сохранить данные для таблицы и всех ее потомков, установите для параметра |
WriteXml(String, XmlWriteMode) |
Записывает текущие данные и по возможности схему для DataTable, используя указанный файл и заданное перечисление XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified file and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(String, XmlWriteMode, Boolean) |
Записывает текущие данные и по возможности схему для DataTable, используя указанный файл и заданное перечисление XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified file and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(TextWriter) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента TextWriter.Writes the current contents of the DataTable as XML using the specified TextWriter. |
WriteXml(TextWriter, Boolean) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента TextWriter.Writes the current contents of the DataTable as XML using the specified TextWriter. Чтобы сохранить данные для таблицы и всех ее потомков, установите для параметра |
WriteXml(TextWriter, XmlWriteMode) |
Записывает текущие данные и по возможности схему для DataTable с помощью указанных TextWriter и XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified TextWriter and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(TextWriter, XmlWriteMode, Boolean) |
Записывает текущие данные и по возможности схему для DataTable с помощью указанных TextWriter и XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified TextWriter and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(XmlWriter) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента XmlWriter.Writes the current contents of the DataTable as XML using the specified XmlWriter. |
WriteXml(XmlWriter, Boolean) |
Записывает текущее содержимое DataTable как XML с использованием указанного элемента XmlWriter.Writes the current contents of the DataTable as XML using the specified XmlWriter. |
WriteXml(XmlWriter, XmlWriteMode) |
Записывает текущие данные и по возможности схему для DataTable с помощью указанных XmlWriter и XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified XmlWriter and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXml(XmlWriter, XmlWriteMode, Boolean) |
Записывает текущие данные и по возможности схему для DataTable с помощью указанных XmlWriter и XmlWriteMode.Writes the current data, and optionally the schema, for the DataTable using the specified XmlWriter and XmlWriteMode. Чтобы записать схему, задайте в параметре |
WriteXmlSchema(Stream) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы в указанный поток.Writes the current data structure of the DataTable as an XML schema to the specified stream. |
WriteXmlSchema(Stream, Boolean) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы в указанный поток.Writes the current data structure of the DataTable as an XML schema to the specified stream. Чтобы сохранить схему для таблицы и всех ее потомков, установите для параметра |
WriteXmlSchema(String) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы в указанный файл.Writes the current data structure of the DataTable as an XML schema to the specified file. |
WriteXmlSchema(String, Boolean) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы в указанный файл.Writes the current data structure of the DataTable as an XML schema to the specified file. Чтобы сохранить схему для таблицы и всех ее потомков, установите для параметра |
WriteXmlSchema(TextWriter) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы, используя указанный класс TextWriter.Writes the current data structure of the DataTable as an XML schema using the specified TextWriter. |
WriteXmlSchema(TextWriter, Boolean) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы, используя указанный класс TextWriter.Writes the current data structure of the DataTable as an XML schema using the specified TextWriter. Чтобы сохранить схему для таблицы и всех ее потомков, установите для параметра |
WriteXmlSchema(XmlWriter) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы, используя указанный класс XmlWriter.Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter. |
WriteXmlSchema(XmlWriter, Boolean) |
Записывает текущую структуру данных таблицы DataTable в виде XML-схемы, используя указанный класс XmlWriter.Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter. Чтобы сохранить схему для таблицы и всех ее потомков, установите для параметра |
События
ColumnChanged |
Происходит после изменения значения указанного объекта DataColumn в DataRow.Occurs after a value has been changed for the specified DataColumn in a DataRow. |
ColumnChanging |
Происходит при изменении значения указанного объекта DataColumn в DataRow.Occurs when a value is being changed for the specified DataColumn in a DataRow. |
Disposed |
Добавляет обработчик события для ожидания события Disposed в компоненте.Adds an event handler to listen to the Disposed event on the component. (Унаследовано от MarshalByValueComponent) |
Initialized |
Происходит после инициализации таблицы DataTable.Occurs after the DataTable is initialized. |
RowChanged |
Происходит после успешного изменения DataRow.Occurs after a DataRow has been changed successfully. |
RowChanging |
Происходит при изменении объекта DataRow.Occurs when a DataRow is changing. |
RowDeleted |
Происходит после удаления строки таблицы.Occurs after a row in the table has been deleted. |
RowDeleting |
Происходит перед удалением строки таблицы.Occurs before a row in the table is about to be deleted. |
TableCleared |
Происходит после очистки DataTable.Occurs after a DataTable is cleared. |
TableClearing |
Происходит, когда очищается таблица DataTable.Occurs when a DataTable is cleared. |
TableNewRow |
Происходит, когда вставляется новая строка DataRow.Occurs when a new DataRow is inserted. |
Явные реализации интерфейса
IListSource.ContainsListCollection |
Описание этого члена см. в разделе ContainsListCollection.For a description of this member, see ContainsListCollection. |
IListSource.GetList() |
Описание этого члена см. в разделе GetList().For a description of this member, see GetList(). |
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Заполняет объект сведений о сериализации данными, необходимыми для сериализации DataTable.Populates a serialization information object with the data needed to serialize the DataTable. |
IXmlSerializable.GetSchema() |
Описание этого члена см. в разделе GetSchema().For a description of this member, see GetSchema(). |
IXmlSerializable.ReadXml(XmlReader) |
Описание этого члена см. в разделе ReadXml(XmlReader).For a description of this member, see ReadXml(XmlReader). |
IXmlSerializable.WriteXml(XmlWriter) |
Описание этого члена см. в разделе WriteXml(XmlWriter).For a description of this member, see WriteXml(XmlWriter). |
Методы расширения
AsDataView(DataTable) |
Создает и возвращает объект DataView с поддержкой LINQ.Creates and returns a LINQ-enabled DataView object. |
AsEnumerable(DataTable) |
Возвращает объект IEnumerable<T>, где универсальный параметр |
Применяется к
Потокобезопасность
Этот тип является надежным для многопоточных операций чтения.This type is safe for multithreaded read operations. Необходимо синхронизировать любые операции записи.You must synchronize any write operations.