Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
DataTable Class

Represents one table of in-memory data.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)
Visual Basic
<SerializableAttribute> _
Public Class DataTable _
    Inherits MarshalByValueComponent _
    Implements IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable,  _
    IXmlSerializable
C#
[SerializableAttribute]
public class DataTable : MarshalByValueComponent, IListSource, 
    ISupportInitializeNotification, ISupportInitialize, ISerializable, IXmlSerializable
Visual C++
[SerializableAttribute]
public ref class DataTable : public MarshalByValueComponent, 
    IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable, IXmlSerializable
F#
[<SerializableAttribute>]
type DataTable =  
    class
        inherit MarshalByValueComponent
        interface IListSource
        interface ISupportInitializeNotification
        interface ISupportInitialize
        interface ISerializable
        interface IXmlSerializable
    end

The DataTable type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkDataTable()()()Initializes a new instance of the DataTable class with no arguments.
Public methodSupported by the XNA FrameworkDataTable(String)Initializes a new instance of the DataTable class with the specified table name.
Protected methodDataTable(SerializationInfo, StreamingContext)Initializes a new instance of the DataTable class with the SerializationInfo and the StreamingContext.
Public methodSupported by the XNA FrameworkDataTable(String, String)Initializes a new instance of the DataTable class using the specified table name and namespace.
Top
  NameDescription
Public propertySupported by the XNA FrameworkCaseSensitiveIndicates whether string comparisons within the table are case-sensitive.
Public propertySupported by the XNA FrameworkChildRelationsGets the collection of child relations for this DataTable.
Public propertySupported by the XNA FrameworkColumnsGets the collection of columns that belong to this table.
Public propertySupported by the XNA FrameworkConstraintsGets the collection of constraints maintained by this table.
Public propertySupported by the XNA FrameworkContainerGets the container for the component. (Inherited from MarshalByValueComponent.)
Public propertySupported by the XNA FrameworkDataSetGets the DataSet to which this table belongs.
Public propertySupported by the XNA FrameworkDefaultViewGets a customized view of the table that may include a filtered view, or a cursor position.
Public propertySupported by the XNA FrameworkDesignModeGets a value indicating whether the component is currently in design mode. (Inherited from MarshalByValueComponent.)
Public propertySupported by the XNA FrameworkDisplayExpressionGets or sets the expression that returns a value used to represent this table in the user interface. The DisplayExpression property lets you display the name of this table in a user interface.
Protected propertySupported by the XNA FrameworkEventsGets the list of event handlers that are attached to this component. (Inherited from MarshalByValueComponent.)
Public propertySupported by the XNA FrameworkExtendedPropertiesGets the collection of customized user information.
Public propertySupported by the XNA FrameworkHasErrorsGets 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.
Public propertySupported by the XNA FrameworkIsInitializedGets a value that indicates whether the DataTable is initialized.
Public propertySupported by the XNA FrameworkLocaleGets or sets the locale information used to compare strings within the table.
Public propertySupported by the XNA FrameworkMinimumCapacityGets or sets the initial starting size for this table.
Public propertySupported by the XNA FrameworkNamespaceGets or sets the namespace for the XML representation of the data stored in the DataTable.
Public propertySupported by the XNA FrameworkParentRelationsGets the collection of parent relations for this DataTable.
Public propertySupported by the XNA FrameworkPrefixGets or sets the namespace for the XML representation of the data stored in the DataTable.
Public propertySupported by the XNA FrameworkPrimaryKeyGets or sets an array of columns that function as primary keys for the data table.
Public propertyRemotingFormatGets or sets the serialization format.
Public propertySupported by the XNA FrameworkRowsGets the collection of rows that belong to this table.
Public propertySupported by the XNA FrameworkSiteGets or sets an System.ComponentModel..::.ISite for the DataTable. (Overrides MarshalByValueComponent..::.Site.)
Public propertySupported by the XNA FrameworkTableNameGets or sets the name of the DataTable.
Top
  NameDescription
Public methodSupported by the XNA FrameworkAcceptChangesCommits all the changes made to this table since the last time AcceptChanges was called.
Public methodSupported by the XNA FrameworkBeginInitBegins the initialization of a DataTable that is used on a form or used by another component. The initialization occurs at run time.
Public methodSupported by the XNA FrameworkBeginLoadDataTurns off notifications, index maintenance, and constraints while loading data.
Public methodSupported by the XNA FrameworkClearClears the DataTable of all data.
Public methodSupported by the XNA FrameworkCloneClones the structure of the DataTable, including all DataTable schemas and constraints.
Public methodSupported by the XNA FrameworkComputeComputes the given expression on the current rows that pass the filter criteria.
Public methodSupported by the XNA FrameworkCopyCopies both the structure and data for this DataTable.
Public methodSupported by the XNA FrameworkCreateDataReaderReturns a DataTableReader corresponding to the data within this DataTable.
Protected methodSupported by the XNA FrameworkCreateInstanceInfrastructure. Creates a new instance of DataTable.
Public methodSupported by the XNA FrameworkDispose()()()Releases all resources used by the MarshalByValueComponent. (Inherited from MarshalByValueComponent.)
Protected methodSupported by the XNA FrameworkDispose(Boolean)Releases the unmanaged resources used by the MarshalByValueComponent and optionally releases the managed resources. (Inherited from MarshalByValueComponent.)
Public methodSupported by the XNA FrameworkEndInitEnds the initialization of a DataTable that is used on a form or used by another component. The initialization occurs at run time.
Public methodSupported by the XNA FrameworkEndLoadDataTurns on notifications, index maintenance, and constraints after loading data.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from MarshalByValueComponent.)
Public methodSupported by the XNA FrameworkGetChanges()()()Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges was last called.
Public methodSupported by the XNA FrameworkGetChanges(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.
Public methodStatic memberSupported by the XNA FrameworkGetDataTableSchemaThis method returns an XmlSchemaSet instance containing the Web Services Description Language (WSDL) that describes the DataTable for Web Services.
Public methodSupported by the XNA FrameworkGetErrorsGets an array of DataRow objects that contain errors.
Public methodSupported by the XNA FrameworkGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetObjectDataPopulates a serialization information object with the data needed to serialize the DataTable.
Protected methodSupported by the XNA FrameworkGetRowTypeInfrastructure. Gets the row type.
Protected methodSupported by the XNA FrameworkGetSchemaInfrastructure. For a description of this member, see IXmlSerializable..::.GetSchema.
Public methodSupported by the XNA FrameworkGetServiceGets the implementer of the IServiceProvider. (Inherited from MarshalByValueComponent.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkImportRowCopies a DataRow into a DataTable, preserving any property settings, as well as original and current values.
Public methodSupported by the XNA FrameworkLoad(IDataReader)Fills a DataTable with values from a data source using the supplied IDataReader. If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.
Public methodSupported by the XNA FrameworkLoad(IDataReader, LoadOption)Fills a DataTable with values from a data source using the supplied IDataReader. If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows according to the value of the loadOption parameter.
Public methodSupported by the XNA FrameworkLoad(IDataReader, LoadOption, FillErrorEventHandler)Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.
Public methodSupported by the XNA FrameworkLoadDataRow(array<Object>[]()[], Boolean)Finds and updates a specific row. If no matching row is found, a new row is created using the given values.
Public methodSupported by the XNA FrameworkLoadDataRow(array<Object>[]()[], LoadOption)Finds and updates a specific row. If no matching row is found, a new row is created using the given values.
Protected methodSupported by the XNA FrameworkMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkMerge(DataTable)Merge the specified DataTable with the current DataTable.
Public methodSupported by the XNA FrameworkMerge(DataTable, Boolean)Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current DataTable.
Public methodSupported by the XNA FrameworkMerge(DataTable, Boolean, MissingSchemaAction)Merge the specified DataTable with the current DataTable, indicating whether to preserve changes and how to handle missing schema in the current DataTable.
Public methodSupported by the XNA FrameworkNewRowCreates a new DataRow with the same schema as the table.
Protected methodSupported by the XNA FrameworkNewRowArrayInfrastructure. Returns an array of DataRow.
Protected methodSupported by the XNA FrameworkNewRowFromBuilderCreates a new row from an existing row.
Protected methodSupported by the XNA FrameworkOnColumnChangedRaises the ColumnChanged event.
Protected methodSupported by the XNA FrameworkOnColumnChangingRaises the ColumnChanging event.
Protected methodSupported by the XNA FrameworkOnPropertyChangingRaises the PropertyChanged event.
Protected methodOnRemoveColumnNotifies the DataTable that a DataColumn is being removed.
Protected methodSupported by the XNA FrameworkOnRowChangedRaises the RowChanged event.
Protected methodSupported by the XNA FrameworkOnRowChangingRaises the RowChanging event.
Protected methodSupported by the XNA FrameworkOnRowDeletedRaises the RowDeleted event.
Protected methodSupported by the XNA FrameworkOnRowDeletingRaises the RowDeleting event.
Protected methodSupported by the XNA FrameworkOnTableClearedRaises the TableCleared event.
Protected methodSupported by the XNA FrameworkOnTableClearingRaises the TableClearing event.
Protected methodSupported by the XNA FrameworkOnTableNewRowRaises the TableNewRow event.
Public methodSupported by the XNA FrameworkReadXml(Stream)Reads XML schema and data into the DataTable using the specified Stream.
Public methodSupported by the XNA FrameworkReadXml(String)Reads XML schema and data into the DataTable from the specified file.
Public methodSupported by the XNA FrameworkReadXml(TextReader)Reads XML schema and data into the DataTable using the specified TextReader.
Public methodSupported by the XNA FrameworkReadXml(XmlReader)Reads XML Schema and Data into the DataTable using the specified XmlReader.
Public methodSupported by the XNA FrameworkReadXmlSchema(Stream)Reads an XML schema into the DataTable using the specified stream.
Public methodSupported by the XNA FrameworkReadXmlSchema(String)Reads an XML schema into the DataTable from the specified file.
Public methodSupported by the XNA FrameworkReadXmlSchema(TextReader)Reads an XML schema into the DataTable using the specified TextReader.
Public methodSupported by the XNA FrameworkReadXmlSchema(XmlReader)Reads an XML schema into the DataTable using the specified XmlReader.
Protected methodSupported by the XNA FrameworkReadXmlSerializableInfrastructure. Reads from an XML stream.
Public methodSupported by the XNA FrameworkRejectChangesRolls back all changes that have been made to the table since it was loaded, or the last time AcceptChanges was called.
Public methodSupported by the XNA FrameworkResetResets the DataTable to its original state.
Public methodSupported by the XNA FrameworkSelect()()()Gets an array of all DataRow objects.
Public methodSupported by the XNA FrameworkSelect(String)Gets an array of all DataRow objects that match the filter criteria.
Public methodSupported by the XNA FrameworkSelect(String, String)Gets an array of all DataRow objects that match the filter criteria, in the specified sort order.
Public methodSupported by the XNA FrameworkSelect(String, String, DataViewRowState)Gets an array of all DataRow objects that match the filter in the order of the sort that match the specified state.
Public methodSupported by the XNA FrameworkToStringGets the TableName and DisplayExpression, if there is one as a concatenated string. (Overrides MarshalByValueComponent..::.ToString()()().)
Public methodSupported by the XNA FrameworkWriteXml(Stream)Writes the current contents of the DataTable as XML using the specified Stream.
Public methodSupported by the XNA FrameworkWriteXml(String)Writes the current contents of the DataTable as XML using the specified file.
Public methodSupported by the XNA FrameworkWriteXml(TextWriter)Writes the current contents of the DataTable as XML using the specified TextWriter.
Public methodSupported by the XNA FrameworkWriteXml(XmlWriter)Writes the current contents of the DataTable as XML using the specified XmlWriter.
Public methodSupported by the XNA FrameworkWriteXml(Stream, Boolean)Writes the current contents of the DataTable as XML using the specified Stream. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(Stream, XmlWriteMode)Writes the current data, and optionally the schema, for the DataTable to the specified file using the specified XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.
Public methodSupported by the XNA FrameworkWriteXml(String, Boolean)Writes the current contents of the DataTable as XML using the specified file. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(String, XmlWriteMode)Writes the current data, and optionally the schema, for the DataTable using the specified file and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.
Public methodSupported by the XNA FrameworkWriteXml(TextWriter, Boolean)Writes the current contents of the DataTable as XML using the specified TextWriter. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(TextWriter, XmlWriteMode)Writes the current data, and optionally the schema, for the DataTable using the specified TextWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.
Public methodSupported by the XNA FrameworkWriteXml(XmlWriter, Boolean)Writes the current contents of the DataTable as XML using the specified XmlWriter.
Public methodSupported by the XNA FrameworkWriteXml(XmlWriter, XmlWriteMode)Writes the current data, and optionally the schema, for the DataTable using the specified XmlWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.
Public methodSupported by the XNA FrameworkWriteXml(Stream, XmlWriteMode, Boolean)Writes the current data, and optionally the schema, for the DataTable to the specified file using the specified XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(String, XmlWriteMode, Boolean)Writes the current data, and optionally the schema, for the DataTable using the specified file and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(TextWriter, XmlWriteMode, Boolean)Writes the current data, and optionally the schema, for the DataTable using the specified TextWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXml(XmlWriter, XmlWriteMode, Boolean)Writes the current data, and optionally the schema, for the DataTable using the specified XmlWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema. To save the data for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXmlSchema(Stream)Writes the current data structure of the DataTable as an XML schema to the specified stream.
Public methodSupported by the XNA FrameworkWriteXmlSchema(String)Writes the current data structure of the DataTable as an XML schema to the specified file.
Public methodSupported by the XNA FrameworkWriteXmlSchema(TextWriter)Writes the current data structure of the DataTable as an XML schema using the specified TextWriter.
Public methodSupported by the XNA FrameworkWriteXmlSchema(XmlWriter)Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter.
Public methodSupported by the XNA FrameworkWriteXmlSchema(Stream, Boolean)Writes the current data structure of the DataTable as an XML schema to the specified stream. To save the schema for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXmlSchema(String, Boolean)Writes the current data structure of the DataTable as an XML schema to the specified file. To save the schema for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXmlSchema(TextWriter, Boolean)Writes the current data structure of the DataTable as an XML schema using the specified TextWriter. To save the schema for the table and all its descendants, set the writeHierarchy parameter to true.
Public methodSupported by the XNA FrameworkWriteXmlSchema(XmlWriter, Boolean)Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter. To save the schema for the table and all its descendants, set the writeHierarchy parameter to true.
Top
  NameDescription
Public eventSupported by the XNA FrameworkColumnChangedOccurs after a value has been changed for the specified DataColumn in a DataRow.
Public eventSupported by the XNA FrameworkColumnChangingOccurs when a value is being changed for the specified DataColumn in a DataRow.
Public eventSupported by the XNA FrameworkDisposedAdds an event handler to listen to the Disposed event on the component. (Inherited from MarshalByValueComponent.)
Public eventSupported by the XNA FrameworkInitializedOccurs after the DataTable is initialized.
Public eventSupported by the XNA FrameworkRowChangedOccurs after a DataRow has been changed successfully.
Public eventSupported by the XNA FrameworkRowChangingOccurs when a DataRow is changing.
Public eventSupported by the XNA FrameworkRowDeletedOccurs after a row in the table has been deleted.
Public eventSupported by the XNA FrameworkRowDeletingOccurs before a row in the table is about to be deleted.
Public eventSupported by the XNA FrameworkTableClearedOccurs after a DataTable is cleared.
Public eventSupported by the XNA FrameworkTableClearingOccurs when a DataTable is cleared.
Public eventSupported by the XNA FrameworkTableNewRowOccurs when a new DataRow is inserted.
Top
  NameDescription
Public Extension MethodAsDataViewCreates and returns a LINQ-enabled DataView object. (Defined by DataTableExtensions.)
Public Extension MethodAsEnumerableReturns an IEnumerable<(Of <(T>)>) object, where the generic parameter T is DataRow. This object can be used in a LINQ expression or method query. (Defined by DataTableExtensions.)
Top
  NameDescription
Protected fieldSupported by the XNA FrameworkfInitInProgressInfrastructure. Checks whether initialization is in progress. The initialization occurs at run time.
Top
  NameDescription
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkIListSource..::.ContainsListCollectionFor a description of this member, see IListSource..::.ContainsListCollection.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIListSource..::.GetListFor a description of this member, see IListSource..::.GetList.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIXmlSerializable..::.GetSchemaFor a description of this member, see IXmlSerializable..::.GetSchema.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIXmlSerializable..::.ReadXmlFor a description of this member, see IXmlSerializable..::.ReadXml.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIXmlSerializable..::.WriteXmlFor a description of this member, see IXmlSerializable..::.WriteXml.
Top

The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView.

When accessing DataTable objects, note that they are conditionally case sensitive. 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. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A DataSet can contain two DataTable objects that have the same TableName property value but different Namespace property values. For more information about working with DataTable objects, see Creating a DataTable (ADO.NET).

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). For more information about adding DataColumn objects, see Adding Columns to a DataTable (ADO.NET).

To add rows to a DataTable, you must first use the NewRow method to return a new DataRow object. The NewRow method returns a row with the schema of the DataTable, as it is defined by the table's DataColumnCollection. The maximum number of rows that a DataTable can store is 16,777,216. For more information, see Adding Data to a DataTable.

The DataTable also contains a collection of Constraint objects that can be used to ensure the integrity of the data. For more information, see DataTable Constraints (ADO.NET).

There are many DataTable events that can be used to determine when changes are made to a table. These include RowChanged, RowChanging, RowDeleting, and RowDeleted. For more information about the events that can be used with a DataTable, see Handling DataTable Events (ADO.NET).

When an instance of DataTable is created, some of the read/write properties are set to initial values. For a list of these values, see the DataTable..::.DataTable constructor topic.

NoteNote

The DataSet and DataTable objects inherit from MarshalByValueComponent, and support the ISerializable interface for .NET Framework remoting. These are the only ADO.NET objects that you can use for .NET Framework remoting.

TopicLocation
Cómo: Crear DataTablesAcceso a datos en Visual Studio
Cómo: Crear DataTablesAcceso a datos en Visual Studio

The following example creates two DataTable objects and one DataRelation object, and adds the new objects to a DataSet. The tables are then displayed in a DataGridView control.

Visual Basic
' 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 DataTable = 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 DataTable = 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
 
C#
// 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");
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is safe for multithreaded read operations. You must synchronize any write operations.

Biblioteca de clases de .NET Framework
DataTable (Clase)

Representa una tabla de datos en memoria.

Espacio de nombres:  System.Data
Ensamblado:  System.Data (en System.Data.dll)
Visual Basic
<SerializableAttribute> _
Public Class DataTable _
    Inherits MarshalByValueComponent _
    Implements IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable,  _
    IXmlSerializable
C#
[SerializableAttribute]
public class DataTable : MarshalByValueComponent, IListSource, 
    ISupportInitializeNotification, ISupportInitialize, ISerializable, IXmlSerializable
Visual C++
[SerializableAttribute]
public ref class DataTable : public MarshalByValueComponent, 
    IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable, IXmlSerializable
F#
[<SerializableAttribute>]
type DataTable =  
    class
        inherit MarshalByValueComponent
        interface IListSource
        interface ISupportInitializeNotification
        interface ISupportInitialize
        interface ISerializable
        interface IXmlSerializable
    end

El tipo DataTable expone los siguientes miembros.

  NombreDescripción
Método públicoCompatible con XNA FrameworkDataTable()()()Inicializa una nueva instancia de la clase DataTable sin argumentos.
Método públicoCompatible con XNA FrameworkDataTable(String)Inicializa una nueva instancia de la clase DataTable con el nombre de tabla especificado.
Método protegidoDataTable(SerializationInfo, StreamingContext)Inicializa una nueva instancia de la clase DataTable con el objeto SerializationInfo y la estructura StreamingContext.
Método públicoCompatible con XNA FrameworkDataTable(String, String)Inicializa una nueva instancia de la clase DataTable utilizando el nombre de tabla y el espacio de nombres especificados.
Arriba
  NombreDescripción
Propiedad públicaCompatible con XNA FrameworkCaseSensitiveIndica si las comparaciones de cadenas en la tabla distinguen entre mayúsculas y minúsculas.
Propiedad públicaCompatible con XNA FrameworkChildRelationsObtiene la colección de relaciones secundarias para este DataTable.
Propiedad públicaCompatible con XNA FrameworkColumnsObtiene la colección de columnas que pertenecen a esta tabla.
Propiedad públicaCompatible con XNA FrameworkConstraintsObtiene la colección de restricciones mantenidas por esta tabla.
Propiedad públicaCompatible con XNA FrameworkContainerObtiene el contenedor del componente. (Se hereda de MarshalByValueComponent).
Propiedad públicaCompatible con XNA FrameworkDataSetObtiene el objeto DataSet al que pertenece esta tabla.
Propiedad públicaCompatible con XNA FrameworkDefaultViewObtiene una vista personalizada de la tabla que puede incluir una vista filtrada o una posición del cursor.
Propiedad públicaCompatible con XNA FrameworkDesignModeObtiene un valor que indica si el componente está actualmente en modo de diseño. (Se hereda de MarshalByValueComponent).
Propiedad públicaCompatible con XNA FrameworkDisplayExpressionObtiene o establece la expresión que devuelve un valor utilizado para representar esta tabla en la interfaz de usuario. La propiedad DisplayExpression permite mostrar el nombre de esta tabla en una interfaz de usuario.
Propiedad protegidaCompatible con XNA FrameworkEventsObtiene la lista de controladores de eventos asociados a este componente. (Se hereda de MarshalByValueComponent).
Propiedad públicaCompatible con XNA FrameworkExtendedPropertiesObtiene la colección de información personalizada del usuario.
Propiedad públicaCompatible con XNA FrameworkHasErrorsObtiene un valor que indica si hay errores en cualquier fila de cualquier tabla del DataSet al que pertenece la tabla.
Propiedad públicaCompatible con XNA FrameworkIsInitializedObtiene un valor que indica si el objeto DataTable está inicializado.
Propiedad públicaCompatible con XNA FrameworkLocaleObtiene o establece la información de configuración regional que se utiliza para comparar cadenas de la tabla.
Propiedad públicaCompatible con XNA FrameworkMinimumCapacityObtiene o establece el tamaño inicial para esta tabla.
Propiedad públicaCompatible con XNA FrameworkNamespaceObtiene o establece el espacio de nombres para la representación XML de los datos almacenados en el objeto DataTable.
Propiedad públicaCompatible con XNA FrameworkParentRelationsObtiene la colección de relaciones primarias para este DataTable.
Propiedad públicaCompatible con XNA FrameworkPrefixObtiene o establece el espacio de nombres para la representación XML de los datos almacenados en el objeto DataTable.
Propiedad públicaCompatible con XNA FrameworkPrimaryKeyObtiene o establece una matriz de columnas que funcionan como claves principales para la tabla de datos.
Propiedad públicaRemotingFormatObtiene o establece el formato de serialización.
Propiedad públicaCompatible con XNA FrameworkRowsObtiene la colección de filas que pertenecen a esta tabla.
Propiedad públicaCompatible con XNA FrameworkSiteObtiene o establece una interfaz System.ComponentModel..::.ISite para el objeto DataTable. (Invalida a MarshalByValueComponent..::.Site).
Propiedad públicaCompatible con XNA FrameworkTableNameObtiene o establece el nombre de DataTable.
Arriba
  NombreDescripción
Método públicoCompatible con XNA FrameworkAcceptChangesConfirma todos los cambios realizados en esta tabla desde la última vez que se llamó a AcceptChanges.
Método públicoCompatible con XNA FrameworkBeginInitActiva la inicialización de un objeto DataTable que se emplea en un formulario o que utiliza otro componente. La inicialización se produce en tiempo de ejecución.
Método públicoCompatible con XNA FrameworkBeginLoadDataDesactiva notificaciones, mantenimiento de índices y restricciones mientras se cargan datos.
Método públicoCompatible con XNA FrameworkClearBorra el DataTable de todos los datos.
Método públicoCompatible con XNA FrameworkCloneClona la estructura de DataTable, incluidos todos los esquemas y restricciones de DataTable.
Método públicoCompatible con XNA FrameworkComputeCalcula la expresión dada de las filas actuales que cumplen los criterios de filtro.
Método públicoCompatible con XNA FrameworkCopyCopia la estructura y los datos para este objeto DataTable.
Método públicoCompatible con XNA FrameworkCreateDataReaderDevuelve un objeto DataTableReader que corresponde a los datos incluidos en este objeto DataTable.
Método protegidoCompatible con XNA FrameworkCreateInstanceInfraestructura. Crea una nueva instancia de DataTable.
Método públicoCompatible con XNA FrameworkDispose()()()Libera todos los recursos utilizados por el objeto MarshalByValueComponent. (Se hereda de MarshalByValueComponent).
Método protegidoCompatible con XNA FrameworkDispose(Boolean)Libera los recursos no administrados usados por MarshalByValueComponent y, opcionalmente, los recursos administrados. (Se hereda de MarshalByValueComponent).
Método públicoCompatible con XNA FrameworkEndInitFinaliza la inicialización de un objeto DataTable que se emplea en un formulario o que usa otro componente. La inicialización se produce en tiempo de ejecución.
Método públicoCompatible con XNA FrameworkEndLoadDataActiva notificaciones, mantenimiento de índices y restricciones después de cargar datos.
Método públicoCompatible con XNA FrameworkEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoCompatible con XNA FrameworkFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de MarshalByValueComponent).
Método públicoCompatible con XNA FrameworkGetChanges()()()Obtiene una copia del objeto DataTable que contiene todos los cambios que se le han realizado desde que se cargó o se llamó a AcceptChanges por última vez.
Método públicoCompatible con XNA FrameworkGetChanges(DataRowState)Obtiene una copia del objeto DataTable que contiene todos los cambios que se le han realizado desde la última vez que se cargó, o desde que se llamó a AcceptChanges, filtrado por DataRowState.
Método públicoMiembro estáticoCompatible con XNA FrameworkGetDataTableSchemaEste método devuelve una instancia de XmlSchemaSet que contiene el Lenguaje de descripción de servicios Web (WSDL) que describe DataTable para servicios Web.
Método públicoCompatible con XNA FrameworkGetErrorsObtiene una matriz de objetos DataRow que contienen errores.
Método públicoCompatible con XNA FrameworkGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetObjectDataRellena un objeto de información de serialización con los datos necesarios para serializar la clase DataTable.
Método protegidoCompatible con XNA FrameworkGetRowTypeInfraestructura. Obtiene el tipo de fila.
Método protegidoCompatible con XNA FrameworkGetSchemaInfraestructura. Para obtener una descripción de este miembro, vea IXmlSerializable..::.GetSchema.
Método públicoCompatible con XNA FrameworkGetServiceObtiene el implementador de IServiceProvider. (Se hereda de MarshalByValueComponent).
Método públicoCompatible con XNA FrameworkGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método públicoCompatible con XNA FrameworkImportRowCopia un DataRow en un DataTable conservando los valores de propiedad, así como los valores originales y actuales.
Método públicoCompatible con XNA FrameworkLoad(IDataReader)Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada. Si el objeto DataTable ya contiene filas, los datos de entrada del origen de datos se combinan con las filas existentes.
Método públicoCompatible con XNA FrameworkLoad(IDataReader, LoadOption)Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada. Si el objeto DataTable ya contiene las filas, los datos de entrada del origen de datos se combinan con las filas existentes conforme al valor del parámetro loadOption.
Método públicoCompatible con XNA FrameworkLoad(IDataReader, LoadOption, FillErrorEventHandler)Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada y un delegado de control de errores.
Método públicoCompatible con XNA FrameworkLoadDataRow(array<Object>[]()[], Boolean)Busca y actualiza una fila específica. Si no encuentra ninguna fila coincidente, se crea una nueva con los valores dados.
Método públicoCompatible con XNA FrameworkLoadDataRow(array<Object>[]()[], LoadOption)Busca y actualiza una fila específica. Si no encuentra ninguna fila coincidente, se crea una nueva con los valores dados.
Método protegidoCompatible con XNA FrameworkMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoCompatible con XNA FrameworkMerge(DataTable)Combina el objeto DataTable especificado con el objeto DataTable actual.
Método públicoCompatible con XNA FrameworkMerge(DataTable, Boolean)Combina el objeto DataTable especificado con el objeto DataTable actual, indicando si se deben conservar los cambios en el objeto DataTable actual.
Método públicoCompatible con XNA FrameworkMerge(DataTable, Boolean, MissingSchemaAction)Combina el objeto DataTable especificado con el objeto DataTable actual, indicando si se van a conservar los cambios y cómo se va a controlar el esquema que falta en el objeto DataTable actual.
Método públicoCompatible con XNA FrameworkNewRowCrea un nuevo DataRow con el mismo esquema que la tabla.
Método protegidoCompatible con XNA FrameworkNewRowArrayInfraestructura. Devuelve una matriz de objetos DataRow.
Método protegidoCompatible con XNA FrameworkNewRowFromBuilderCrea una nueva fila a partir de una existente.
Método protegidoCompatible con XNA FrameworkOnColumnChangedProvoca el evento ColumnChanged.
Método protegidoCompatible con XNA FrameworkOnColumnChangingProvoca el evento ColumnChanging.
Método protegidoCompatible con XNA FrameworkOnPropertyChangingProvoca el evento PropertyChanged.
Método protegidoOnRemoveColumnNotifica a DataTable que se ha quitado un DataColumn.
Método protegidoCompatible con XNA FrameworkOnRowChangedProvoca el evento RowChanged.
Método protegidoCompatible con XNA FrameworkOnRowChangingProvoca el evento RowChanging.
Método protegidoCompatible con XNA FrameworkOnRowDeletedProvoca el evento RowDeleted.
Método protegidoCompatible con XNA FrameworkOnRowDeletingProvoca el evento RowDeleting.
Método protegidoCompatible con XNA FrameworkOnTableClearedProvoca el evento TableCleared.
Método protegidoCompatible con XNA FrameworkOnTableClearingProvoca el evento TableClearing.
Método protegidoCompatible con XNA FrameworkOnTableNewRowProvoca el evento TableNewRow.
Método públicoCompatible con XNA FrameworkReadXml(Stream)Lee los datos y el esquema XML en el objeto DataTable mediante el objeto Stream especificado.
Método públicoCompatible con XNA FrameworkReadXml(String)Lee los datos y el esquema XML en el objeto DataTable desde el archivo especificado.
Método públicoCompatible con XNA FrameworkReadXml(TextReader)Lee los datos y el esquema XML en el objeto DataTable mediante el objeto TextReader especificado.
Método públicoCompatible con XNA FrameworkReadXml(XmlReader)Lee datos y el esquema XML en el objeto DataTable mediante el objeto XmlReader especificado.
Método públicoCompatible con XNA FrameworkReadXmlSchema(Stream)Lee un esquema XML en el objeto DataTable utilizando la secuencia especificada.
Método públicoCompatible con XNA FrameworkReadXmlSchema(String)Lee un esquema XML en el objeto DataTable desde el archivo especificado.
Método públicoCompatible con XNA FrameworkReadXmlSchema(TextReader)Lee un esquema XML en el objeto DataTable utilizando el objeto TextReader especificado.
Método públicoCompatible con XNA FrameworkReadXmlSchema(XmlReader)Lee un esquema XML en el objeto DataTable utilizando el objeto XmlReader especificado.
Método protegidoCompatible con XNA FrameworkReadXmlSerializableInfraestructura. Lee de una secuencia XML.
Método públicoCompatible con XNA FrameworkRejectChangesDeshace todos los cambios que se hayan realizado en la tabla desde que se cargó o se llamó a AcceptChanges por última vez.
Método públicoCompatible con XNA FrameworkResetRestablece el estado original del objeto DataTable.
Método públicoCompatible con XNA FrameworkSelect()()()Obtiene una matriz de todos los objetos DataRow.
Método públicoCompatible con XNA FrameworkSelect(String)Obtiene una matriz de todos los objetos DataRow que coinciden con los criterios de filtro.
Método públicoCompatible con XNA FrameworkSelect(String, String)Obtiene una matriz de todos los objetos DataRow que coinciden con los criterios de filtro, en el criterio de ordenación especificado.
Método públicoCompatible con XNA FrameworkSelect(String, String, DataViewRowState)Obtiene una matriz de todos los objetos DataRow que coinciden con el filtro en el orden de clasificación y que coinciden con el estado especificado.
Método públicoCompatible con XNA FrameworkToStringObtiene TableName y DisplayExpression, si hay alguna, como cadena concatenada. (Invalida a MarshalByValueComponent..::.ToString()()()).
Método públicoCompatible con XNA FrameworkWriteXml(Stream)Escribe el contenido actual del objeto DataTable como elemento XML utilizando el objeto Stream especificado.
Método públicoCompatible con XNA FrameworkWriteXml(String)Escribe el contenido actual del objeto DataTable como elemento XML utilizando el archivo especificado.
Método públicoCompatible con XNA FrameworkWriteXml(TextWriter)Escribe el contenido actual del objeto DataTable como XML utilizando el objeto TextWriter especificado.
Método públicoCompatible con XNA FrameworkWriteXml(XmlWriter)Escribe el contenido actual del objeto DataTable como XML utilizando el objeto XmlWriter especificado.
Método públicoCompatible con XNA FrameworkWriteXml(Stream, Boolean)Escribe el contenido actual del objeto DataTable como elemento XML utilizando el objeto Stream especificado. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(Stream, XmlWriteMode)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable en el archivo indicado mediante la enumeración XmlWriteMode especificada. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema.
Método públicoCompatible con XNA FrameworkWriteXml(String, Boolean)Escribe el contenido actual del objeto DataTable como elemento XML utilizando el archivo especificado. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(String, XmlWriteMode)Escribe los datos actuales y, de forma opcional, el esquema para el DataTable mediante el archivo y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema.
Método públicoCompatible con XNA FrameworkWriteXml(TextWriter, Boolean)Escribe el contenido actual del objeto DataTable como XML utilizando el objeto TextWriter especificado. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(TextWriter, XmlWriteMode)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable mediante el objeto TextWriter y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema.
Método públicoCompatible con XNA FrameworkWriteXml(XmlWriter, Boolean)Escribe el contenido actual del objeto DataTable como XML utilizando el objeto XmlWriter especificado.
Método públicoCompatible con XNA FrameworkWriteXml(XmlWriter, XmlWriteMode)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable mediante el objeto XmlWriter y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema.
Método públicoCompatible con XNA FrameworkWriteXml(Stream, XmlWriteMode, Boolean)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable en el archivo indicado mediante la enumeración XmlWriteMode especificada. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(String, XmlWriteMode, Boolean)Escribe los datos actuales y, de forma opcional, el esquema para el DataTable mediante el archivo y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(TextWriter, XmlWriteMode, Boolean)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable mediante el objeto TextWriter y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXml(XmlWriter, XmlWriteMode, Boolean)Escribe los datos actuales y, de forma opcional, el esquema para el objeto DataTable mediante el objeto XmlWriter y la enumeración XmlWriteMode especificados. Para escribir el esquema, establezca el valor del parámetro mode en WriteSchema. Para guardar los datos de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(Stream)Escribe en la secuencia especificada la estructura de datos actual del objeto DataTable como esquema XML.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(String)Escribe en el archivo especificado la estructura de datos actual del objeto DataTable como esquema XML.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(TextWriter)Escribe la estructura de datos actual del objeto DataTable como esquema XML, utilizando el objeto TextWriter especificado.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(XmlWriter)Escribe la estructura de datos actual del objeto DataTable como esquema XML, utilizando el objeto XmlWriter especificado.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(Stream, Boolean)Escribe en la secuencia especificada la estructura de datos actual del objeto DataTable como esquema XML. Para guardar el esquema de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(String, Boolean)Escribe en el archivo especificado la estructura de datos actual del objeto DataTable como esquema XML. Para guardar el esquema de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(TextWriter, Boolean)Escribe la estructura de datos actual del objeto DataTable como esquema XML, utilizando el objeto TextWriter especificado. Para guardar el esquema de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Método públicoCompatible con XNA FrameworkWriteXmlSchema(XmlWriter, Boolean)Escribe la estructura de datos actual del objeto DataTable como esquema XML, utilizando el objeto XmlWriter especificado. Para guardar el esquema de la tabla y de todos sus descendientes, establezca el parámetro writeHierarchy en true.
Arriba
  NombreDescripción
Evento públicoCompatible con XNA FrameworkColumnChangedSe produce cuando se ha cambiado un valor para el DataColumn especificado de un DataRow.
Evento públicoCompatible con XNA FrameworkColumnChangingSe produce cuando se ha cambiado un valor para el DataColumn especificado de un DataRow.
Evento públicoCompatible con XNA FrameworkDisposedAgrega un controlador de eventos para escuchar el evento Disposed en el componente. (Se hereda de MarshalByValueComponent).
Evento públicoCompatible con XNA FrameworkInitializedSe produce después de inicializar DataTable.
Evento públicoCompatible con XNA FrameworkRowChangedSe produce después de cambiar correctamente un objeto DataRow.
Evento públicoCompatible con XNA FrameworkRowChangingSe produce cuando se cambia un DataRow.
Evento públicoCompatible con XNA FrameworkRowDeletedSe produce después de eliminar una fila de la tabla.
Evento públicoCompatible con XNA FrameworkRowDeletingSe produce cuando se va a eliminar una fila de la tabla.
Evento públicoCompatible con XNA FrameworkTableClearedSe produce después de borrar un objeto DataTable.
Evento públicoCompatible con XNA FrameworkTableClearingSe produce cuando se borra un objeto DataTable.
Evento públicoCompatible con XNA FrameworkTableNewRowSe produce cuando se inserta un nuevo objeto DataRow.
Arriba
  NombreDescripción
Método de extensión públicoAsDataViewCrea y devuelve un objeto DataView habilitado para LINQ. (Definido por DataTableExtensions).
Método de extensión públicoAsEnumerableDevuelve un objeto IEnumerable<(Of <(T>)>), donde el parámetro T genérico es DataRow. Este objeto puede usarse en una expresión LINQ o en una consulta de método. (Definido por DataTableExtensions).
Arriba
  NombreDescripción
Campo protegidoCompatible con XNA FrameworkfInitInProgressInfraestructura. Comprueba si la inicialización está en curso. La inicialización se produce en tiempo de ejecución.
Arriba
  NombreDescripción
Implementación explícita de interfacesPropiedad privadaCompatible con XNA FrameworkIListSource..::.ContainsListCollectionPara obtener una descripción de este miembro, vea IListSource..::.ContainsListCollection.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIListSource..::.GetListPara obtener una descripción de este miembro, vea IListSource..::.GetList.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIXmlSerializable..::.GetSchemaPara obtener una descripción de este miembro, vea IXmlSerializable..::.GetSchema.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIXmlSerializable..::.ReadXmlPara obtener una descripción de este miembro, vea IXmlSerializable..::.ReadXml.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIXmlSerializable..::.WriteXmlPara obtener una descripción de este miembro, vea IXmlSerializable..::.WriteXml.
Arriba

DataTable es un objeto central de la biblioteca ADO.NET. Entre los objetos que utilizan DataTable se incluyen DataSet y DataView.

Al obtener acceso a los objetos DataTable, hay que tener en cuenta que éstos distinguen entre mayúsculas y minúsculas condicionalmente. Por ejemplo, si un objeto DataTable se denomina "mydatatable" y otro "Mydatatable", la cadena que se utilice para buscar una de las tablas se considerará que distingue entre mayúsculas y minúsculas. Sin embargo, si existe "mydatatable" pero no existe "Mydatatable", se considerará que la cadena de búsqueda no distingue entre mayúsculas y minúsculas. Un objeto DataSet puede contener dos objetos DataTable que tengan el mismo valor para la propiedad TableName y distintos valores para la propiedad Namespace. Para obtener más información sobre el trabajo con los objetos DataTable, vea Crear DataTable (ADO.NET).

Si se va a crear un DataTable mediante programación, en primer lugar se debe definir su esquema agregando objetos DataColumn al DataColumnCollection (al que se obtiene acceso mediante la propiedad Columns). Para obtener más información sobre la adición de objetos DataColumn, vea Agregar columnas a la DataTable (ADO.NET).

Para agregar filas a DataTable, en primer lugar se debe utilizar el método NewRow para devolver un nuevo objeto DataRow. El método NewRow devuelve una fila con el esquema de DataTable, tal como lo define el DataColumnCollection de la tabla. El número máximo de filas que un DataTable puede almacenar es 16.777.216. Para obtener más información, vea Agregar datos a DataTable.

DataTable también contiene una colección de objetos Constraint que se pueden utilizar para asegurar la integridad de los datos. Para obtener más información, vea Restricciones de DataTable (ADO.NET).

Hay muchos eventos DataTable que se pueden utilizar para determinar cuándo se realizan cambios en una tabla. Entre éstos se incluyen RowChanged, RowChanging, RowDeleting y RowDeleted. Para obtener más información sobre los eventos que se pueden utilizar con un objeto DataTable, vea Control de eventos DataTable (ADO.NET).

Cuando se crea una instancia de DataTable, se establecen algunas propiedades de lectura y escritura en valores iniciales. Para obtener una lista de esos valores, vea el tema sobre el constructor DataTable..::.DataTable.

NotaNota

Los objetos DataSet y DataTable heredan de MarshalByValueComponent y admiten la interfaz ISerializable para la comunicación remota de .NET Framework. Éstos son los únicos objetos de ADO.NET que se pueden utilizar para la comunicación remota de .NET Framework.

TopicLocation
Cómo: Crear DataTablesAcceso a datos en Visual Studio
Cómo: Crear DataTablesAcceso a datos en Visual Studio

En el ejemplo siguiente se crean dos objetos DataTable y un objeto DataRelation, y se agregan los nuevos objetos a DataSet. A continuación, las tablas se muestran en un control DataGridView.

Visual Basic
' 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 DataTable = 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 DataTable = 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
 
C#
// 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");
}

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Este tipo es seguro para operaciones de lectura multiproceso. Debe sincronizar cualquier operación de escritura.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker