DataRow Класс
Определение
public ref class DataRow
public class DataRow
[System.Serializable]
public class DataRow
type DataRow = class
[<System.Serializable>]
type DataRow = class
Public Class DataRow
- Наследование
-
DataRow
- Атрибуты
Примеры
В следующем примере создается новый DataRow путем вызова NewRow метода DataTable объекта.The following example creates a new DataRow by calling the NewRow method of the DataTable object.
private void CreateNewDataRow()
{
// Use the MakeTable function below to create a new table.
DataTable table;
table = MakeNamesTable();
// Once a table has been created, use the
// NewRow to create a DataRow.
DataRow row;
row = table.NewRow();
// Then add the new row to the collection.
row["fName"] = "John";
row["lName"] = "Smith";
table.Rows.Add(row);
foreach(DataColumn column in table.Columns)
Console.WriteLine(column.ColumnName);
dataGrid1.DataSource=table;
}
private DataTable MakeNamesTable()
{
// Create a new DataTable titled 'Names.'
DataTable namesTable = new DataTable("Names");
// Add three column objects to the table.
DataColumn idColumn = new DataColumn();
idColumn.DataType = System.Type.GetType("System.Int32");
idColumn.ColumnName = "id";
idColumn.AutoIncrement = true;
namesTable.Columns.Add(idColumn);
DataColumn fNameColumn = new DataColumn();
fNameColumn.DataType = System.Type.GetType("System.String");
fNameColumn.ColumnName = "Fname";
fNameColumn.DefaultValue = "Fname";
namesTable.Columns.Add(fNameColumn);
DataColumn lNameColumn = new DataColumn();
lNameColumn.DataType = System.Type.GetType("System.String");
lNameColumn.ColumnName = "LName";
namesTable.Columns.Add(lNameColumn);
// Create an array for DataColumn objects.
DataColumn [] keys = new DataColumn [1];
keys[0] = idColumn;
namesTable.PrimaryKey = keys;
// Return the new DataTable.
return namesTable;
}
Private Sub CreateNewDataRow()
' Use the MakeTable function below to create a new table.
Dim table As DataTable
table = MakeNamesTable()
' Once a table has been created, use the
' NewRow to create a DataRow.
Dim row As DataRow
row = table.NewRow()
' Then add the new row to the collection.
row("fName") = "John"
row("lName") = "Smith"
table.Rows.Add(row)
Dim column As DataColumn
For Each column in table.Columns
Console.WriteLine(column.ColumnName)
Next
DataGrid1.DataSource=table
End Sub
Private Function MakeNamesTable() As DataTable
' Create a new DataTable titled 'Names.'
Dim namesTable As New DataTable("Names")
' Add three column objects to the table.
Dim idColumn As New DataColumn()
idColumn.DataType = System.Type.GetType("System.Int32")
idColumn.ColumnName = "id"
idColumn.AutoIncrement = True
namesTable.Columns.Add(idColumn)
Dim fNameColumn As New DataColumn()
fNameColumn.DataType = System.Type.GetType("System.String")
fNameColumn.ColumnName = "Fname"
fNameColumn.DefaultValue = "Fname"
namesTable.Columns.Add(fNameColumn)
Dim lNameColumn As New DataColumn()
lNameColumn.DataType = System.Type.GetType("System.String")
lNameColumn.ColumnName = "LName"
namesTable.Columns.Add(lNameColumn)
' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = idColumn
namesTable.PrimaryKey = keys
' Return the new DataTable.
MakeNamesTable = namesTable
End Function
Комментарии
DataRowОбъекты и DataColumn являются основными компонентами DataTable .The DataRow and DataColumn objects are primary components of a DataTable. Используйте DataRow объект и его свойства и методы для извлечения и вычисления, а также для вставки, удаления и обновления значений в DataTable .Use the DataRow object and its properties and methods to retrieve and evaluate; and insert, delete, and update the values in the DataTable. Объект DataRowCollection представляет фактические DataRow объекты в DataTable , а объект DataColumnCollection содержит DataColumn объекты, описывающие схему DataTable .The DataRowCollection represents the actual DataRow objects in the DataTable, and the DataColumnCollection contains the DataColumn objects that describe the schema of the DataTable. Используйте Перегруженное свойство, Item[] чтобы вернуть или задать значение DataColumn .Use the overloaded Item[] property to return or set the value of a DataColumn.
Используйте HasVersion Свойства и, IsNull чтобы определить состояние конкретного значения строки, а также RowState свойство для определения состояния строки относительно ее родителя DataTable .Use the HasVersion and IsNull properties to determine the status of a particular row value, and the RowState property to determine the state of the row relative to its parent DataTable.
Чтобы создать новый DataRow объект, используйте NewRow метод DataTable объекта.To create a new DataRow, use the NewRow method of the DataTable object. После создания нового DataRow метода используйте метод, Add чтобы добавить новый объект DataRow в DataRowCollection .After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Наконец, вызовите AcceptChanges метод объекта, DataTable чтобы подтвердить добавление.Finally, call the AcceptChanges method of the DataTable object to confirm the addition. Дополнительные сведения о добавлении данных в см DataTable . в разделе Добавление данных в таблицу DataTable.For more information about adding data to a DataTable, see Adding Data to a DataTable.
Можно удалить DataRow из из, DataRowCollection вызвав Remove метод DataRowCollection объекта или путем вызова Delete метода для этого класса DataRow .You can delete a DataRow from the DataRowCollection by calling the Remove method of the DataRowCollection, or by calling the Delete method of the DataRow object. RemoveМетод удаляет строку из коллекции.The Remove method removes the row from the collection. Напротив, Delete помечает DataRow для удаления.In contrast, Delete marks the DataRow for removal. Фактическое удаление происходит при вызове AcceptChanges метода.The actual removal occurs when you call AcceptChanges method. Вызывая метод Delete , можно программно проверить, какие строки отмечены для удаления, прежде чем удалять их.By calling Delete, you can programmatically check which rows are marked for removal before actually deleting them. Дополнительные сведения см. в разделе Удаление DataRow.For more information, see DataRow Deletion.
Конструкторы
DataRow(DataRowBuilder) |
Инициализирует новый экземпляр DataRow.Initializes a new instance of the DataRow. Создает строку из построителя.Constructs a row from the builder. Только для внутреннего использования.Only for internal usage. |
Свойства
HasErrors |
Получает значение, показывающее, есть ли ошибки в строке.Gets a value that indicates whether there are errors in a row. |
Item[DataColumn, DataRowVersion] |
Получает указанную версию данных, сохраненных в указанном объекте DataColumn.Gets the specified version of data stored in the specified DataColumn. |
Item[DataColumn] |
Возвращает или задает данные, сохраненные в указанном объекте DataColumn.Gets or sets the data stored in the specified DataColumn. |
Item[Int32, DataRowVersion] |
Получает данные, сохраненные в столбце, указанном по индексу и версии извлекаемых данных.Gets the data stored in the column, specified by index and version of the data to retrieve. |
Item[Int32] |
Возвращает или задает данные, сохраненные в столбце, указанном по индексу.Gets or sets the data stored in the column specified by index. |
Item[String, DataRowVersion] |
Получает указанную версию данных, сохраненных в именованном столбце.Gets the specified version of data stored in the named column. |
Item[String] |
Возвращает или задает данные, сохраненные в столбце, указанном по имени.Gets or sets the data stored in the column specified by name. |
ItemArray |
Возвращает или задает все значения для этой строки с помощью массива.Gets or sets all the values for this row through an array. |
RowError |
Возвращает или задает настраиваемое описание ошибки для строки.Gets or sets the custom error description for a row. |
RowState |
Получает текущее состояние строки, относящееся к ее отношению к коллекции DataRowCollection.Gets the current state of the row with regard to its relationship to the DataRowCollection. |
Table |
Получает объект DataTable, для которого эта строка имеет схему.Gets the DataTable for which this row has a schema. |
Методы
AcceptChanges() |
Фиксирует все изменения, внесенные в эту строку со времени последнего вызова метода AcceptChanges().Commits all the changes made to this row since the last time AcceptChanges() was called. |
BeginEdit() |
Начинает операцию изменения объекта DataRow.Starts an edit operation on a DataRow object. |
CancelEdit() |
Отменяет текущее изменение строки.Cancels the current edit on the row. |
ClearErrors() |
Очищает ошибки для строки.Clears the errors for the row. Это относится к свойству RowError и ошибкам, установленным с помощью метода SetColumnError(Int32, String).This includes the RowError and errors set with SetColumnError(Int32, String). |
Delete() | |
EndEdit() |
Прекращает изменение строки.Ends the edit occurring on the row. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetChildRows(DataRelation) |
Получает дочерние строки этого объекта DataRow с помощью указанного объекта DataRelation.Gets the child rows of this DataRow using the specified DataRelation. |
GetChildRows(DataRelation, DataRowVersion) |
Получает дочерние строки объекта DataRow с помощью указанных объектов DataRelation и DataRowVersion.Gets the child rows of a DataRow using the specified DataRelation, and DataRowVersion. |
GetChildRows(String) |
Получает дочерние строки объекта DataRow с помощью указанного свойства RelationName объекта DataRelation.Gets the child rows of a DataRow using the specified RelationName of a DataRelation. |
GetChildRows(String, DataRowVersion) |
Получает дочерние строки объекта DataRow с помощью указанного свойства RelationName объектов DataRelation и DataRowVersion.Gets the child rows of a DataRow using the specified RelationName of a DataRelation, and DataRowVersion. |
GetColumnError(DataColumn) |
Получает описание ошибки указанного объекта DataColumn.Gets the error description of the specified DataColumn. |
GetColumnError(Int32) |
Получает описание ошибки для столбца, указанного по индексу.Gets the error description for the column specified by index. |
GetColumnError(String) |
Получает описание ошибки для столбца, указанного по имени.Gets the error description for a column, specified by name. |
GetColumnsInError() |
Получает массив столбцов с ошибками.Gets an array of columns that have errors. |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetParentRow(DataRelation) |
Получает родительскую строку объекта DataRow с помощью указанного объекта DataRelation.Gets the parent row of a DataRow using the specified DataRelation. |
GetParentRow(DataRelation, DataRowVersion) |
Получает родительскую строку объекта DataRow с помощью указанных объектов DataRelation и DataRowVersion.Gets the parent row of a DataRow using the specified DataRelation, and DataRowVersion. |
GetParentRow(String) |
Получает родительскую строку объекта DataRow с помощью указанного свойства RelationName объекта DataRelation.Gets the parent row of a DataRow using the specified RelationName of a DataRelation. |
GetParentRow(String, DataRowVersion) |
Получает родительскую строку объекта DataRow с помощью указанного свойства RelationName объектов DataRelation и DataRowVersion.Gets the parent row of a DataRow using the specified RelationName of a DataRelation, and DataRowVersion. |
GetParentRows(DataRelation) |
Получает родительские строки объекта DataRow с помощью указанного объекта DataRelation.Gets the parent rows of a DataRow using the specified DataRelation. |
GetParentRows(DataRelation, DataRowVersion) |
Получает родительские строки объекта DataRow с помощью указанных объектов DataRelation и DataRowVersion.Gets the parent rows of a DataRow using the specified DataRelation, and DataRowVersion. |
GetParentRows(String) |
Получает родительские строки объекта DataRow с помощью указанного свойства RelationName объекта DataRelation.Gets the parent rows of a DataRow using the specified RelationName of a DataRelation. |
GetParentRows(String, DataRowVersion) |
Получает родительские строки объекта DataRow с помощью указанного свойства RelationName объектов DataRelation и DataRowVersion.Gets the parent rows of a DataRow using the specified RelationName of a DataRelation, and DataRowVersion. |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
HasVersion(DataRowVersion) |
Получает значение, показывающее, существует ли указанная версия.Gets a value that indicates whether a specified version exists. |
IsNull(DataColumn) |
Получает значение, показывающее, содержит ли указанный объект DataColumn значение null.Gets a value that indicates whether the specified DataColumn contains a null value. |
IsNull(DataColumn, DataRowVersion) |
Получает значение, показывающее, содержит ли указанные объекты DataColumn и DataRowVersion значение null.Gets a value that indicates whether the specified DataColumn and DataRowVersion contains a null value. |
IsNull(Int32) |
Получает значение, показывающее, содержит ли столбец по указанному индексу значение null.Gets a value that indicates whether the column at the specified index contains a null value. |
IsNull(String) |
Получает значение, показывающее, содержит ли названный столбец значение null.Gets a value that indicates whether the named column contains a null value. |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
RejectChanges() |
Отменяет все изменения, внесенные в строку после последнего вызова метода AcceptChanges().Rejects all changes made to the row since AcceptChanges() was last called. |
SetAdded() |
Изменяет значение свойства RowState объекта DataRow на |
SetColumnError(DataColumn, String) |
Задает описание ошибки для столбца, указанного как DataColumn.Sets the error description for a column specified as a DataColumn. |
SetColumnError(Int32, String) |
Задает описание ошибки для столбца, указанного по индексу.Sets the error description for a column specified by index. |
SetColumnError(String, String) |
Задает описание ошибки для столбца, указанного по имени.Sets the error description for a column specified by name. |
SetModified() |
Изменяет значение свойства RowState объекта DataRow на |
SetNull(DataColumn) |
Задает значение null указанному параметру DataColumn.Sets the value of the specified DataColumn to a null value. |
SetParentRow(DataRow) |
Задает родительскую строку DataRow с указанным новым родительским объектом DataRow.Sets the parent row of a DataRow with specified new parent DataRow. |
SetParentRow(DataRow, DataRelation) |
Задает родительскую строку DataRow с указанными новыми родительскими объектами DataRow и DataRelation.Sets the parent row of a DataRow with specified new parent DataRow and DataRelation. |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |
Методы расширения
Field<T>(DataRow, DataColumn) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, DataColumn) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, DataColumn) method also supports nullable types. |
Field<T>(DataRow, DataColumn, DataRowVersion) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, DataColumn, DataRowVersion) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, DataColumn, DataRowVersion) method also supports nullable types. |
Field<T>(DataRow, Int32) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, Int32) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, Int32) method also supports nullable types. |
Field<T>(DataRow, Int32, DataRowVersion) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, Int32, DataRowVersion) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, Int32, DataRowVersion) method also supports nullable types. |
Field<T>(DataRow, String) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, String) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, String) method also supports nullable types. |
Field<T>(DataRow, String, DataRowVersion) |
Обеспечивает строго типизированный доступ к каждому значению столбца в указанной строке.Provides strongly-typed access to each of the column values in the specified row. Метод Field<T>(DataRow, String, DataRowVersion) также поддерживает типы, допускающие значения null.The Field<T>(DataRow, String, DataRowVersion) method also supports nullable types. |
SetField<T>(DataRow, DataColumn, T) |
Задает новое значение для указанного столбца в DataRow.Sets a new value for the specified column in the DataRow. Метод SetField<T>(DataRow, DataColumn, T) также поддерживает типы, допускающие значения null.The SetField<T>(DataRow, DataColumn, T) method also supports nullable types. |
SetField<T>(DataRow, Int32, T) |
Задает новое значение для указанного столбца в вызванном методе DataRow.Sets a new value for the specified column in the DataRow the method is called on. Метод SetField<T>(DataRow, Int32, T) также поддерживает типы, допускающие значения null.The SetField<T>(DataRow, Int32, T) method also supports nullable types. |
SetField<T>(DataRow, String, T) |
Задает новое значение для указанного столбца в DataRow.Sets a new value for the specified column in the DataRow. Метод SetField<T>(DataRow, String, T) также поддерживает типы, допускающие значения null.The SetField<T>(DataRow, String, T) method also supports nullable types. |
Применяется к
Потокобезопасность
Этот тип является надежным для многопоточных операций чтения.This type is safe for multithreaded read operations. Необходимо синхронизировать любые операции записи.You must synchronize any write operations.