Export (0) Print
Expand All

DataTable Class

Represents one table of in-memory data.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)

'Declaration
<SerializableAttribute> _
Public Class DataTable _
	Inherits MarshalByValueComponent _
	Implements IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable,  _
	IXmlSerializable

The DataTable type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkDataTableInitializes 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 FrameworkDisposeReleases 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 FrameworkGetChangesGets 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 the default hash function. (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(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(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. 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.
Public methodSupported by the XNA FrameworkSelectGets 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.

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.

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.

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.

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
How to: Create DataTablesData Access in 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.

' 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
 

This sample demonstrates how to create a DataTable manually with specific schema definitions:

  • 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# and Visual Basic projects with this code sample can be found on Developer Code Samples.

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

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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.

Show:
© 2014 Microsoft