Sideway
output.to from Sideway
Draft for Information Only

Content

System.Data Namespace Component
DataTable Class
 Definition
  In this article
 Examples
 Remarks
 Constructors
 Fields
 Properties
 Methods
 Events
 Explicit Interface Implementations
 Extension Methods
 Applies to
   .NET Core
   .NET Framework
   .NET Standard
   Xamarin.Android
   Xamarin.iOS
   Xamarin.Mac
 Thread Safety
 See also
 Examples
 Source/Reference

System.Data Namespace Component

The System.Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources.

DataTable Class

Definition

Namespace:
System.Data
Assemblies:
System.Data.Common.dll, System.Data.dll, netstandard.dll

Represents one table of in-memory data.

In this article

  1. Definition
  2. Examples
  3. Remarks
  4. Constructors
  5. Fields
  6. Properties
  7. Methods
  8. Events
  9. Explicit Interface Implementations
  10. Extension Methods
  11. Applies to
  12. Thread Safety
  13. See also
C#
[System.Serializable]
public class DataTable : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
Inheritance
Object MarshalByValueComponent DataTable
Derived
TypedTableBase<T>
Attributes
SerializableAttribute
Implements
IListSource ISupportInitialize ISupportInitializeNotification ISerializable IXmlSerializable

Examples

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.

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");
}

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.

C#
using System;
using System.Data;

class Program {
   static void Main(string[] args) {
      // Create two tables and add them into the DataSet
      DataTable orderTable = CreateOrderTable();
      DataTable orderDetailTable = CreateOrderDetailTable();
      DataSet salesSet = new DataSet();
      salesSet.Tables.Add(orderTable);
      salesSet.Tables.Add(orderDetailTable);

      // Set the relations between the tables and create the related constraint.
      salesSet.Relations.Add("OrderOrderDetail", orderTable.Columns["OrderId"], orderDetailTable.Columns["OrderId"], true);

      Console.WriteLine("After creating the foreign key constriant, you will see the following error if inserting order detail with the wrong OrderId: ");
      try {
         DataRow errorRow = orderDetailTable.NewRow();
         errorRow[0] = 1;
         errorRow[1] = "O0007";
         orderDetailTable.Rows.Add(errorRow);
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
      Console.WriteLine();

      // Insert the rows into the table
      InsertOrders(orderTable);
      InsertOrderDetails(orderDetailTable);

      Console.WriteLine("The initial Order table.");
      ShowTable(orderTable);

      Console.WriteLine("The OrderDetail table.");
      ShowTable(orderDetailTable);

      // Use the Aggregate-Sum on the child table column to get the result.
      DataColumn colSub = new DataColumn("SubTotal", typeof(Decimal), "Sum(Child.LineTotal)");
      orderTable.Columns.Add(colSub);

      // Compute the tax by referencing the SubTotal expression column.
      DataColumn colTax = new DataColumn("Tax", typeof(Decimal), "SubTotal*0.1");
      orderTable.Columns.Add(colTax);

      // If the OrderId is 'Total', compute the due on all orders; or compute the due on this order.
      DataColumn colTotal = new DataColumn("TotalDue", typeof(Decimal), "IIF(OrderId='Total',Sum(SubTotal)+Sum(Tax),SubTotal+Tax)");
      orderTable.Columns.Add(colTotal);

      DataRow row = orderTable.NewRow();
      row["OrderId"] = "Total";
      orderTable.Rows.Add(row);

      Console.WriteLine("The Order table with the expression columns.");
      ShowTable(orderTable);

      Console.WriteLine("Press any key to exit.....");
      Console.ReadKey();
   }

   private static DataTable CreateOrderTable() {
      DataTable orderTable = new DataTable("Order");

      // Define one column.
      DataColumn colId = new DataColumn("OrderId", typeof(String));
      orderTable.Columns.Add(colId);

      DataColumn colDate = new DataColumn("OrderDate", typeof(DateTime));
      orderTable.Columns.Add(colDate);

      // Set the OrderId column as the primary key.
      orderTable.PrimaryKey = new DataColumn[] { colId };

      return orderTable;
   }

   private static DataTable CreateOrderDetailTable() {
      DataTable orderDetailTable = new DataTable("OrderDetail");

      // Define all the columns once.
      DataColumn[] cols ={
                                  new DataColumn("OrderDetailId",typeof(Int32)),
                                  new DataColumn("OrderId",typeof(String)),
                                  new DataColumn("Product",typeof(String)),
                                  new DataColumn("UnitPrice",typeof(Decimal)),
                                  new DataColumn("OrderQty",typeof(Int32)),
                                  new DataColumn("LineTotal",typeof(Decimal),"UnitPrice*OrderQty")
                              };

      orderDetailTable.Columns.AddRange(cols);
      orderDetailTable.PrimaryKey = new DataColumn[] { orderDetailTable.Columns["OrderDetailId"] };
     return orderDetailTable;
   }

   private static void InsertOrders(DataTable orderTable) {
      // Add one row once.
      DataRow row1 = orderTable.NewRow();
      row1["OrderId"] = "O0001";
      row1["OrderDate"] = new DateTime(2013, 3, 1);
      orderTable.Rows.Add(row1);

      DataRow row2 = orderTable.NewRow();
      row2["OrderId"] = "O0002";
      row2["OrderDate"] = new DateTime(2013, 3, 12);
      orderTable.Rows.Add(row2);

      DataRow row3 = orderTable.NewRow();
      row3["OrderId"] = "O0003";
      row3["OrderDate"] = new DateTime(2013, 3, 20);
      orderTable.Rows.Add(row3);
   }

   private static void InsertOrderDetails(DataTable orderDetailTable) {
      // Use an Object array to insert all the rows .
      // Values in the array are matched sequentially to the columns, based on the order in which they appear in the table.
      Object[] rows = {
                                 new Object[]{1,"O0001","Mountain Bike",1419.5,36},
                                 new Object[]{2,"O0001","Road Bike",1233.6,16},
                                 new Object[]{3,"O0001","Touring Bike",1653.3,32},
                                 new Object[]{4,"O0002","Mountain Bike",1419.5,24},
                                 new Object[]{5,"O0002","Road Bike",1233.6,12},
                                 new Object[]{6,"O0003","Mountain Bike",1419.5,48},
                                 new Object[]{7,"O0003","Touring Bike",1653.3,8},
                             };

      foreach (Object[] row in rows) {
         orderDetailTable.Rows.Add(row);
      }
   }

   private static void ShowTable(DataTable table) {
      foreach (DataColumn col in table.Columns) {
         Console.Write("{0,-14}", col.ColumnName);
      }
      Console.WriteLine();

      foreach (DataRow row in table.Rows) {
         foreach (DataColumn col in table.Columns) {
            if (col.DataType.Equals(typeof(DateTime)))
               Console.Write("{0,-14:d}", row[col]);
            else if (col.DataType.Equals(typeof(Decimal)))
               Console.Write("{0,-14:C}", row[col]);
            else
               Console.Write("{0,-14}", row[col]);           
         }
         Console.WriteLine();
      }
      Console.WriteLine();
   }
}

Remarks

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.

Note

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.

Constructors

DataTable()

Initializes a new instance of the DataTable class with no arguments.

DataTable(SerializationInfo, StreamingContext)

Initializes a new instance of the DataTable class with the SerializationInfo and the StreamingContext.

DataTable(String)

Initializes a new instance of the DataTable class with the specified table name.

DataTable(String, String)

Initializes a new instance of the DataTable class using the specified table name and namespace.

Fields

fInitInProgress

Checks whether initialization is in progress. The initialization occurs at run time.

Properties

CaseSensitive

Indicates whether string comparisons within the table are case-sensitive.

ChildRelations

Gets the collection of child relations for this DataTable.

Columns

Gets the collection of columns that belong to this table.

Constraints

Gets the collection of constraints maintained by this table.

Container

Gets the container for the component.

(Inherited from MarshalByValueComponent)
DataSet

Gets the DataSet to which this table belongs.

DefaultView

Gets a customized view of the table that may include a filtered view, or a cursor position.

DesignMode

Gets a value indicating whether the component is currently in design mode.

(Inherited from MarshalByValueComponent)
DisplayExpression

Gets 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.

Events

Gets the list of event handlers that are attached to this component.

(Inherited from MarshalByValueComponent)
ExtendedProperties

Gets the collection of customized user information.

HasErrors

Gets a value indicating whether there are errors in any of the rows in any of the tables of the DataSet to which the table belongs.

IsInitialized

Gets a value that indicates whether the DataTable is initialized.

Locale

Gets or sets the locale information used to compare strings within the table.

MinimumCapacity

Gets or sets the initial starting size for this table.

Namespace

Gets or sets the namespace for the XML representation of the data stored in the DataTable.

ParentRelations

Gets the collection of parent relations for this DataTable.

Prefix

Gets or sets the namespace for the XML representation of the data stored in the DataTable.

PrimaryKey

Gets or sets an array of columns that function as primary keys for the data table.

RemotingFormat

Gets or sets the serialization format.

Rows

Gets the collection of rows that belong to this table.

Site

Gets or sets an ISite for the DataTable.

TableName

Gets or sets the name of the DataTable.

Methods

AcceptChanges()

Commits all the changes made to this table since the last time AcceptChanges() was called.

BeginInit()

Begins the initialization of a DataTable that is used on a form or used by another component. The initialization occurs at run time.

BeginLoadData()

Turns off notifications, index maintenance, and constraints while loading data.

Clear()

Clears the DataTable of all data.

Clone()

Clones the structure of the DataTable, including all DataTable schemas and constraints.

Compute(String, String)

Computes the given expression on the current rows that pass the filter criteria.

Copy()

Copies both the structure and data for this DataTable.

CreateDataReader()

Returns a DataTableReader corresponding to the data within this DataTable.

CreateInstance()

Creates a new instance of DataTable.

Dispose()

Releases all resources used by the MarshalByValueComponent.

(Inherited from MarshalByValueComponent)
Dispose(Boolean)

Releases the unmanaged resources used by the MarshalByValueComponent and optionally releases the managed resources.

(Inherited from MarshalByValueComponent)
EndInit()

Ends the initialization of a DataTable that is used on a form or used by another component. The initialization occurs at run time.

EndLoadData()

Turns on notifications, index maintenance, and constraints after loading data.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetChanges()

Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges() was last called.

GetChanges(DataRowState)

Gets a copy of the DataTable containing all changes made to it since it was last loaded, or since AcceptChanges() was called, filtered by DataRowState.

GetDataTableSchema(XmlSchemaSet)

This method returns an XmlSchemaSet instance containing the Web Services Description Language (WSDL) that describes the DataTable for Web Services.

GetErrors()

Gets an array of DataRow objects that contain errors.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

Populates a serialization information object with the data needed to serialize the DataTable.

GetRowType()

Gets the row type.

GetSchema()

For a description of this member, see GetSchema().

GetService(Type)

Gets the implementer of the IServiceProvider.

(Inherited from MarshalByValueComponent)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
ImportRow(DataRow)

Copies a DataRow into a DataTable, preserving any property settings, as well as original and current values.

Load(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.

Load(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.

Load(IDataReader, LoadOption, FillErrorEventHandler)

Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

LoadDataRow(Object[], Boolean)

Finds and updates a specific row. If no matching row is found, a new row is created using the given values.

LoadDataRow(Object[], LoadOption)

Finds and updates a specific row. If no matching row is found, a new row is created using the given values.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Merge(DataTable)

Merge the specified DataTable with the current DataTable.

Merge(DataTable, Boolean)

Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current DataTable.

Merge(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.

NewRow()

Creates a new DataRow with the same schema as the table.

NewRowArray(Int32)

Returns an array of DataRow.

NewRowFromBuilder(DataRowBuilder)

Creates a new row from an existing row.

OnColumnChanged(DataColumnChangeEventArgs)

Raises the ColumnChanged event.

OnColumnChanging(DataColumnChangeEventArgs)

Raises the ColumnChanging event.

OnPropertyChanging(PropertyChangedEventArgs)

Raises the PropertyChanged event.

OnRemoveColumn(DataColumn)

Notifies the DataTable that a DataColumn is being removed.

OnRowChanged(DataRowChangeEventArgs)

Raises the RowChanged event.

OnRowChanging(DataRowChangeEventArgs)

Raises the RowChanging event.

OnRowDeleted(DataRowChangeEventArgs)

Raises the RowDeleted event.

OnRowDeleting(DataRowChangeEventArgs)

Raises the RowDeleting event.

OnTableCleared(DataTableClearEventArgs)

Raises the TableCleared event.

OnTableClearing(DataTableClearEventArgs)

Raises the TableClearing event.

OnTableNewRow(DataTableNewRowEventArgs)

Raises the TableNewRow event.

ReadXml(Stream)

Reads XML schema and data into the DataTable using the specified Stream.

ReadXml(String)

Reads XML schema and data into the DataTable from the specified file.

ReadXml(TextReader)

Reads XML schema and data into the DataTable using the specified TextReader.

ReadXml(XmlReader)

Reads XML Schema and Data into the DataTable using the specified XmlReader.

ReadXmlSchema(Stream)

Reads an XML schema into the DataTable using the specified stream.

ReadXmlSchema(String)

Reads an XML schema into the DataTable from the specified file.

ReadXmlSchema(TextReader)

Reads an XML schema into the DataTable using the specified TextReader.

ReadXmlSchema(XmlReader)

Reads an XML schema into the DataTable using the specified XmlReader.

ReadXmlSerializable(XmlReader)

Reads from an XML stream.

RejectChanges()

Rolls back all changes that have been made to the table since it was loaded, or the last time AcceptChanges() was called.

Reset()

Resets the DataTable to its original state. Reset removes all data, indexes, relations, and columns of the table. If a DataSet includes a DataTable, the table will still be part of the DataSet after the table is reset.

Select()

Gets an array of all DataRow objects.

Select(String)

Gets an array of all DataRow objects that match the filter criteria.

Select(String, String)

Gets an array of all DataRow objects that match the filter criteria, in the specified sort order.

Select(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.

ToString()

Gets the TableName and DisplayExpression, if there is one as a concatenated string.

WriteXml(Stream)

Writes the current contents of the DataTable as XML using the specified Stream.

WriteXml(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.

WriteXml(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.

WriteXml(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.

WriteXml(String)

Writes the current contents of the DataTable as XML using the specified file.

WriteXml(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.

WriteXml(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.

WriteXml(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.

WriteXml(TextWriter)

Writes the current contents of the DataTable as XML using the specified TextWriter.

WriteXml(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.

WriteXml(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.

WriteXml(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.

WriteXml(XmlWriter)

Writes the current contents of the DataTable as XML using the specified XmlWriter.

WriteXml(XmlWriter, Boolean)

Writes the current contents of the DataTable as XML using the specified XmlWriter.

WriteXml(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.

WriteXml(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.

WriteXmlSchema(Stream)

Writes the current data structure of the DataTable as an XML schema to the specified stream.

WriteXmlSchema(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.

WriteXmlSchema(String)

Writes the current data structure of the DataTable as an XML schema to the specified file.

WriteXmlSchema(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.

WriteXmlSchema(TextWriter)

Writes the current data structure of the DataTable as an XML schema using the specified TextWriter.

WriteXmlSchema(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.

WriteXmlSchema(XmlWriter)

Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter.

WriteXmlSchema(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.

Events

ColumnChanged

Occurs after a value has been changed for the specified DataColumn in a DataRow.

ColumnChanging

Occurs when a value is being changed for the specified DataColumn in a DataRow.

Disposed

Adds an event handler to listen to the Disposed event on the component.

(Inherited from MarshalByValueComponent)
Initialized

Occurs after the DataTable is initialized.

RowChanged

Occurs after a DataRow has been changed successfully.

RowChanging

Occurs when a DataRow is changing.

RowDeleted

Occurs after a row in the table has been deleted.

RowDeleting

Occurs before a row in the table is about to be deleted.

TableCleared

Occurs after a DataTable is cleared.

TableClearing

Occurs when a DataTable is cleared.

TableNewRow

Occurs when a new DataRow is inserted.

Explicit Interface Implementations

IListSource.ContainsListCollection

For a description of this member, see ContainsListCollection.

IListSource.GetList()

For a description of this member, see GetList().

IXmlSerializable.GetSchema()

For a description of this member, see GetSchema().

IXmlSerializable.ReadXml(XmlReader)

For a description of this member, see ReadXml(XmlReader).

IXmlSerializable.WriteXml(XmlWriter)

For a description of this member, see WriteXml(XmlWriter).

Extension Methods

AsDataView(DataTable)

Creates and returns a LINQ-enabled DataView object.

AsEnumerable(DataTable)

Returns an IEnumerable<T> object, where the generic parameter T is DataRow. This object can be used in a LINQ expression or method query.

Applies to

.NET Core

3.0 Preview 8 2.2 2.1 2.0 1.1 1.0

.NET Framework

4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0 1.1

.NET Standard

2.1 Preview 2.0

Xamarin.Android

7.1

Xamarin.iOS

10.8

Xamarin.Mac

3.0

Thread Safety

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

See also

 

Examples

Examples of DataTable Class
ASP.NET Code Input:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
       <title>Sample Page</title>
       <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
       <script runat="server" >
           Sub Page_Load()
               Dim xstr As String
               Dim xconn As New System.Data.OleDb.OleDbConnection
               xconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=T:\test.mdb;User Id=admin;Password=;"
               xconn.Open()
               xstr = xstr + "Connection xconn to database test.mdb  is opened successfully.<br />"
               Dim xdata As New System.Data.DataSet
               Dim xadapt As System.Data.OleDb.OleDbDataAdapter
               Dim sql As String = "SELECT * FROM T1"
               xadapt = New System.Data.OleDb.OleDbDataAdapter(sql, xconn)
               xstr = xstr + "Dataadapter xadapt is assigned to SELECT * FROM T1 through xconn successfully.<br />"
               xadapt.Fill(xdata,"T1")
               xdata.DatasetName = "xdata"
               xstr = xstr + "Dataset xdata is filled by xadapt.fill successfully.<br />"
               xstr = xstr + "<br />"
               Dim xtable As System.Data.DataTable = xdata.Tables(0)
               xstr = xstr + "xdata.Table(0) is assigned to DataTable xtable successfully.<br />"
               xstr = xstr + "Dataset of datatable xtable: " + xtable.DataSet.DataSetName + "<br />"
               xstr = xstr + "Tablename of datatable xtable: " + xtable.TableName + "<br />"
               xtable.PrimaryKey= New System.Data.DataColumn(){xdata.tables(0).Columns("id")}
               xstr = xstr + "The primary of datatable xtable: " + xtable.PrimaryKey(0).ColumnName + "<br />"
               xstr = xstr + "The columns of datatable xtable: " + xtable.Columns.ToString + "<br />"
               xstr = xstr + "The rows of datatable xtable: " + xtable.Rows.ToString + "<br />"
               
               xstr = xstr + "<br />"
               xadapt.Dispose()
               xstr = xstr + "Dataadapter xadapt is disposed successfully.<br />"
               xconn.Close()
               xstr = xstr + "Connection xconn is closed successfully.<br />"
               xstr = xstr + "Dataset xdata.tables(T1).rows(0).item(2):" + xdata.Tables("T1").Rows(0).Item("f2") + "<br />"
               xdata.Dispose()
               xstr = xstr + "Dataset xdata is disposed successfully.<br />"
               
               lbl01.Text = xstr
           End Sub
       </script>
    </head>
    <body>
       <% Response.Write ("<h1>This is a Sample Page of DataTable Class</h1>") %>
       <p>
           <%-- Set on Page_Load --%>
           <asp:Label id="lbl01" runat="server" />
       </p>
    </body>
</html>
HTML Web Page Embedded Output:

Source/Reference


©sideway

ID: 201100011 Last Updated: 11/11/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019