What Is a Data Table?

DataTable

data sheet

This entry lacks an overview map . Supplementing related content makes the entry more complete and can be upgraded quickly. Come on!
DataTable
It is a grid virtual table that temporarily stores data (a table representing data in memory.). DataTable is the core object in the ADO dot net library. It can be applied to VB and ASP. It can simply bind the database without code. It has a Microsoft-style user interface.
Other objects that use DataTable include DataSet and DataView.
Chinese name
data sheet
Foreign name
DataTable
Belong to
Grid virtual table that holds data temporarily
Category
Core objects in the ADO dot net library
Application
VB and ASP
DataTable is a grid virtual table (a table representing data in memory) that temporarily holds data. DataTable is the core object in the ADO dot net library. It can be applied to VB and ASP. It can simply bind the database without code. It has a Microsoft-style user interface.
Other objects that use DataTable include DataSet and DataView.
When accessing DataTable objects, please note that they are case sensitive by condition. For example, if one DataTable is named "mydatatable" and the other is named "Mydatatable", the string used to search one of the tables is considered case sensitive. However, if "mydatatable" exists and "Mydatatable" does not exist, the search string is considered case-insensitive. A DataSet can contain several DataTable objects, which have the same TableName property value and different Namespace property values. More information on using the DataTable object.
Create DataTable
DataTable represents a table of in-memory relational data, which can be created and used independently, or used by other .NET Framework objects. The most common case is as a member of a DataSet.
A DataTable object can be created using the corresponding DataTable constructor. You can add it to the DataSet object's Tables collection by using the Add method and add it to the DataSet .
You can also create a DataTable object by using the Fill method or FillSchema method of the DataAdapter object in the DataSet , or using the ReadXml , ReadXmlSchema, or InferXmlSchema methods of the DataSet from a predefined or inferred XML schema. Note that once a DataTable is added as a member to the Tables collection of a DataSet , it cannot be added to the table collection of any other DataSet .
When you first create a DataTable , there is no schema (ie structure). To define the table's schema, you must create a DataColumn object and add it to the table's Columns collection. You can also define primary key columns for a table, and you can create Constraint objects and add them to the table's Constraints collection. After defining the schema for the DataTable , you can add data rows to the table by adding the DataRow object to the Rows collection of the table.
When you create a DataTable , you don't need to provide a value for the TableName property, you can specify it at another time or leave it blank. However, when a table without a TableName value is added to the DataSet , the table will get a default name Table n that increments from "Table" (meaning Table0).
DataTable schema definition
The schema (that is, structure) of a table is represented by columns and constraints. Use a DataColumn object and ForeignKeyConstraint and UniqueConstraint objects to define the schema of the DataTable. Columns in a table can be mapped to columns in a data source, contain values calculated from expressions, auto-increment their values, or contain primary key values.
Referencing columns, relationships, and constraints in a table by name is case sensitive. Therefore, two or more columns, relationships, or constraints with the same name (but different case) can exist in a table. For example, you could have Col1 and col1 . In this case, referencing a column by name must exactly match the case of the column name, or an exception will be thrown. For example, if the table myTable contains columns Col1 and columns col1 , you would refer to Col1 by name as myTable.Columns ["Col1"] , and reference col1 by name as myTable.Columns ["col1"] . Attempting to reference one of these columns in the form myTable.Columns ["COL1"] will generate an exception.
If only one column, relationship, or constraint exists for a particular name, no case sensitivity applies. That is, if no other column, relationship, or constraint object in the table matches the name of that particular column, relationship, or constraint object, you can use any case to refer to the object by name without throwing an exception. For example, if there is only Col1 in the table, you can use my.Columns ["COL1"] for reference.
Working with data in a DataTable
After you create a DataTable in a DataSet, you can perform the same activities that you perform when working with tables in the database. You can add, view, edit, and delete data in the table; you can monitor errors and events; and you can query the data in the table. When modifying the data in the DataTable , you can also verify that the changes are correct and decide whether to accept or reject the changes programmatically.
  • Adding data to a data table
  • Explains how to create new rows and add them to the table.
  • View data in a data table
  • Explains how to access the data in a row, including the original and current versions of the data.
  • Load method
  • Explains how to fill a DataTable with rows through the Load method.
  • DataTable edit
  • Explains how to modify the data in a row, including pending changes to the row, until the proposed changes are validated and accepted.
  • Row status and row version
  • Provides information about the different states of a row.
  • DataRow delete
  • Explains how to remove rows from a table.
  • Line error message
  • Explains how to insert error messages for each row to help resolve data issues in your application.
  • AcceptChanges and RejectChanges
  • Describes how to accept or reject changes to a row.
Constructor
Initializes a new instance of the DataTable class.
Overload this member. For complete information about this member, including syntax, usage, and examples, click the appropriate name in the overload list.
name
Description
DataTable ()
Initializes a new instance of the DataTable class without parameters.
DataTable (String)
Initializes a new instance of the DataTable class with the specified table name.
DataTable (SerializationInfo, StreamingContext)
Initializes a new instance of the DataTable class using SerializationInfo and StreamingContext.
DataTable (String, String)
Initializes a new instance of the DataTable class with the specified table name and namespace.
Attributes
name
Description
CaseSensitive
Indicates whether string comparisons in the table are case sensitive.
ChildRelations
Gets the collection of child relations of this DataTable.
Columns
Gets the collection of columns that belong to the table.
Constraints
Gets the set of constraints maintained by this table.
Container
Gets the container of the component. (Inherited from MarshalByValueComponent.)
DataSet
Gets the DataSet to which this table belongs.
DefaultView
Gets a custom view of a table that may include a filtered view or cursor position.
DesignMode
Gets a value indicating whether the component is currently in design mode. (Inherited from MarshalByValueComponent.)
DisplayExpression
Gets or sets an expression that returns the value used to represent this table in the user interface. The DisplayExpression property is used to display the name of this table in the user interface.
Events
Gets a list of event handlers attached to this component. (Inherited from MarshalByValueComponent.)
ExtendedProperties
Get a collection of custom user information.
HasErrors
Gets a value indicating whether there are errors in any row of any table of the DataSet to which the table belongs.
IsInitialized
Gets a value indicating whether the DataTable has been initialized.
Locale
Gets or sets the locale information used to compare strings in the table.
MinimumCapacity
Gets or sets the initial starting size of the table.
Namespace
Gets or sets the namespace of the XML representation of the data stored in the DataTable.
ParentRelations
Gets the collection of parent relationships for this DataTable.
Prefix
Gets or sets the namespace of the XML representation of the data stored in the DataTable.
PrimaryKey
Gets or sets an array of columns that serve as the primary key of the data table.
RemotingFormat
Gets or sets the serialization format.
Rows
Gets the collection of rows belonging to the table.
Site
Gets or sets the System.ComponentModel.ISite of the DataTable. (Overrides MarshalByValueComponent.Site.)
TableName
Gets or sets the name of the DataTable.
Explicit interface implementation
name
Description
IListSource.GetList
For a description of this member, see IListSource.GetList.
IXmlSerializable.GetSchema
For a description of this member, see IXmlSerializable.GetSchema.
IXmlSerializable.ReadXml
For a description of this member, see IXmlSerializable.ReadXml.
IXmlSerializable.WriteXml
For a description of this member, see IXmlSerializable.WriteXml.
method
name
Description
AcceptChanges
Commit all changes to the table since AcceptChanges was last called.
BeginInit
Begins initialization of a DataTable used on a form or used by another component. Initialization occurs at runtime.
BeginLoadData
Turn off notifications, index maintenance, and constraints when loading data.
Clear
Clear the DataTable of all data.
Clone
Clone a DataTable's structure, including all DataTable schemas and constraints.
Compute
Evaluates the given expression on the current line used to pass the filter.
Copy
Copy the structure and data of the DataTable.
CreateDataReader
Returns a DataTableReader corresponding to the data in this DataTable.
CreateInstance
basic structure. Create a new instance of the DataTable.
Dispose ()
Frees all resources used by MarshalByValueComponent. (Inherited from MarshalByValueComponent.)
Dispose (Boolean)
Release the unmanaged resources used by MarshalByValueComponent. You can also release managed resources in addition. (Inherited from MarshalByValueComponent.)
EndInit
Ends the initialization of a DataTable used on a form or used by another component. Initialization occurs at runtime.
EndLoadData
Turn 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.)
Finalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from MarshalByValueComponent.)
GetChanges ()
Gets a copy of the DataTable that contains all changes made to the dataset since it was loaded or since the last call to AcceptChanges.
GetChanges (DataRowState)
Gets a copy of the DataTable filtered by DataRowState, which contains all changes made to the dataset since it was last loaded or since AcceptChanges was called.
GetDataTableSchema
This method returns an XmlSchemaSet instance containing a Web Services Description Language (WSDL) that describes the DataTable used as a Web service.
GetErrors
Gets an array of DataRow objects containing errors.
GetHashCode
As the default hash function. (Inherited from Object.)
GetObjectData
Populate the serialization information object with the data needed to serialize the DataTable.
GetRowType
basic structure. Get the row type.
GetSchema
basic structure. For a description of this member, see IXmlSerializable.GetSchema.
GetService
Get the implementer of IServiceProvider. (Inherited from MarshalByValueComponent.)
GetType
Gets the Type of the current instance. (Inherited from Object.)
ImportRow
Copy the DataRow into the DataTable, retaining any property settings, as well as the initial and current values.
Load (IDataReader)
Use the provided IDataReader to populate the DataTable with values from a data source. If the DataTable already contains rows, the data passed in from the data source is merged with the existing rows.
Load (IDataReader, LoadOption)
Use the provided IDataReader to populate the DataTable with values from a data source. If the DataTable already contains rows, the data passed in from the data source is merged with the existing rows based on the value of the loadOption parameter.
Load (IDataReader, LoadOption, FillErrorEventHandler)
Fill the DataTable with the values from a data source through the provided IDataReader using an error handling delegate.
LoadDataRow (Object [], Boolean)
Find and update specific rows. If no matching rows are found, a new row is created with the given value.
LoadDataRow (Object [], LoadOption)
Find and update specific rows. If no matching rows are found, a new row is created with the given value.
MemberwiseClone
Creates a shallow copy of the current Object. (Inherited from Object.)
Merge (DataTable)
Merges the specified DataTable with the current DataTable.
Merge (DataTable, Boolean)
Merges the specified DataTable with the current DataTable, indicating whether changes are retained in the current DataTable.
Merge (DataTable, Boolean, MissingSchemaAction)
Merges the specified DataTable with the current DataTable, indicating whether to keep changes in the current DataTable and how to handle missing schemas.
NewRow
Create a new DataRow with the same schema as the table.
NewRowArray
basic structure. Returns an array of DataRow.
NewRowFromBuilder
Create a new row from an existing row.
OnColumnChanged
Raises the ColumnChanged event.
OnColumnChanging
Raises the ColumnChanging event.
OnPropertyChanging
Raises the PropertyChanged event.
OnRemoveColumn
Notify DataTable: DataColumn is being removed.
OnRowChanged
Raises the RowChanged event.
OnRowChanging
Raises the RowChanging event.
OnRowDeleted
Raises the RowDeleted event.
OnRowDeleting
Raises the RowDeleting event.
OnTableCleared
Raises the TableCleared event.
OnTableClearing
Raises the TableClearing event.
OnTableNewRow
Raises the TableNewRow event.
ReadXml (Stream)
Reads the XML schema and data into the DataTable using the specified Stream.
ReadXml (String)
Reads the XML schema and data from the specified file into the DataTable.
ReadXml (TextReader)
Reads the XML schema and data into the DataTable using the specified TextReader.
ReadXml (XmlReader)
Reads the XML schema and data into the DataTable using the specified XmlReader.
ReadXmlSchema (Stream)
Reads an XML schema into a DataTable using the specified stream.
ReadXmlSchema (String)
Reads the XML schema from the specified file into the DataTable.
ReadXmlSchema (TextReader)
Reads the XML schema into the DataTable using the specified TextReader.
ReadXmlSchema (XmlReader)
Reads the XML schema into the DataTable using the specified XmlReader.
ReadXmlSerializable
basic structure. Read from an XML stream.
RejectChanges
Roll back all changes made to the table since it was loaded or since the last call to AcceptChanges.
Reset
Reset the DataTable to its initial state. A reset removes all data, indexes, relationships, and columns from the table. If the data set contains a data table, it will remain part of the data set 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 in the specified sort order and matching the filter criteria.
Select (String, String, DataViewRowState)
Gets an array of all DataRow objects that match the filters in the sort order and the specified state.
ToString
Gets the TableName and DisplayExpression (if one is used as a connection string). (Overrides MarshalByValueComponent.ToString ().)
WriteXml (Stream)
Writes the current contents of the DataTable in XML format using the specified Stream.
WriteXml (String)
Writes the current contents of the DataTable in XML format using the specified file.
WriteXml (TextWriter)
Writes the current contents of the DataTable in XML format using the specified TextWriter.
WriteXml (XmlWriter)
Writes the current contents of the DataTable in XML format using the specified XmlWriter.
WriteXml (Stream, Boolean)
Writes the current contents of the DataTable in XML format using the specified Stream. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (Stream, XmlWriteMode)
Writes the current data of the DataTable to the specified file using the specified XmlWriteMode, and optionally writes the schema to the specified file. To write the schema, set the value of the mode parameter to WriteSchema.
WriteXml (String, Boolean)
Writes the current contents of the DataTable in XML format using the specified file. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (String, XmlWriteMode)
Writes the current data of the DataTable using the specified file and XmlWriteMode (optionally also writes the schema). To write the schema, set the value of the mode parameter to WriteSchema.
WriteXml (TextWriter, Boolean)
Writes the current contents of the DataTable in XML format using the specified TextWriter. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (TextWriter, XmlWriteMode)
Writes the current data of the DataTable using the specified TextWriter and XmlWriteMode, and optionally writes a schema. To write the schema, set the value of the mode parameter to WriteSchema.
WriteXml (XmlWriter, Boolean)
Writes the current contents of the DataTable in XML format using the specified XmlWriter.
WriteXml (XmlWriter, XmlWriteMode)
Writes the current data of the DataTable using the specified XmlWriter and XmlWriteMode, and optionally writes a schema. To write the schema, set the value of the mode parameter to WriteSchema.
WriteXml (Stream, XmlWriteMode, Boolean)
Writes the current data of the DataTable to the specified file using the specified XmlWriteMode, and optionally writes the schema to the specified file. To write the schema, set the value of the mode parameter to WriteSchema. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (String, XmlWriteMode, Boolean)
Writes the current data of the DataTable using the specified file and XmlWriteMode (optionally also writes the schema). To write the schema, set the value of the mode parameter to WriteSchema. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (TextWriter, XmlWriteMode, Boolean)
Writes the current data of the DataTable using the specified TextWriter and XmlWriteMode, and optionally writes a schema. To write the schema, set the value of the mode parameter to WriteSchema. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXml (XmlWriter, XmlWriteMode, Boolean)
Writes the current data of the DataTable using the specified XmlWriter and XmlWriteMode, and optionally writes a schema. To write the schema, set the value of the mode parameter to WriteSchema. To save data for the table and all of its children, set the writeHierarchy parameter to true.
WriteXmlSchema (Stream)
Writes the current data structure of the DataTable to the specified stream as an XML schema.
WriteXmlSchema (String)
Writes the current data structure of the DataTable to the specified file as an XML schema.
WriteXmlSchema (TextWriter)
Writes the current data structure of the DataTable as an XML Schema using the specified TextWriter.
WriteXmlSchema (XmlWriter)
Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter.
WriteXmlSchema (Stream, Boolean)
Writes the current data structure of the DataTable to the specified stream as an XML schema. To save the schema of the table and all of its children, set the writeHierarchy parameter to true.
WriteXmlSchema (String, Boolean)
Writes the current data structure of the DataTable to the specified file as an XML schema. To save the schema of the table and all of its children, set the writeHierarchy parameter to true.
WriteXmlSchema (TextWriter, Boolean)
Writes the current data structure of the DataTable as an XML Schema using the specified TextWriter. To save the schema of the table and all of its children, set the writeHierarchy parameter to true.
WriteXmlSchema (XmlWriter, Boolean)
Writes the current data structure of the DataTable as an XML schema using the specified XmlWriter. To save the schema of the table and all of its children, set the writeHierarchy parameter to true.
Extension method
name
Description
AsDataView
Creates and returns a LINQ-enabled DataView object. (Defined by DataTableExtensions.)
AsEnumerable
Returns an IEnumerable <T> object whose generic parameter T is DataRow. This object can be used in a LINQ expression or method query. (Defined by DataTableExtensions.)
DataTable event
name
Description
ColumnChanged
Occurs when the value of the DataColumn specified in the DataRow is changed.
ColumnChanging
Occurs when the value of the DataColumn specified in the DataRow changes.
Disposed
Add an event handler to listen for the Disposed event on the component. (Inherited from MarshalByValueComponent.)
Initialized
Occurs after the DataTable is initialized.
RowChanged
Occurs after a successful DataRow change.
RowChanging
Occurs when the DataRow is changing.
RowDeleted
Occurs after a row in the table has been deleted.
RowDeleting
Occurs before the rows in the table are to be deleted.
TableCleared
Occurs after the DataTable is cleared.
TableClearing
Occurs after the DataTable is cleared.
TableNewRow
Occurs when a new DataRow is inserted.
DataTable dt = new DataTable ();
dt.Columns.Add ("ID");
dt.Columns.Add ("Name");
DataRow dr = dt.NewRow ();
object [] objs = {1, "Name"};
dr.ItemArray = objs;
dt.Rows.Add (dr);
this.dataGridView1.DataSource = dt;
  (1) CreateaDataTable DataTabledt = newDataTable ("Table_AX");
 (2) AddcolumnsforDataTable // Method1 dt.Columns.Add ("column0", System.Type.GetType ("System.String")); // Method2 DataColumndc = newDataColumn ("column1", System.Type.GetType ("System .Boolean ")); dt.Columns.Add (dc); (3) AddrowsforDataTable // Initializetherow DataRowdr = dt.NewRow (); dr [" column0 "] =" AX "; dr [" column1 "] = true; dt.Rows.Add (dr); // Doesn'tinitializetherow DataRowdr1 = dt.NewRow (); dt.Rows.Add (dr1);
 (4) Selectrow // If Searchthesecondrow is not assigned, use isnull to select DataRow [] drs = dt.Select ("column1isnull"); DataRow [] drss = dt.Select ("column0 = 'AX'");
 (5) CopyDataTableincludedata DataTabledtNew = dt.Copy (); (6) CopyDataTableonlyscheme DataTabledtOnlyScheme = dt.Clone (); (7) Operateonerow // operation on dt // Method1 DataRowdrOperate = dt.Rows [0]; drOperate ["column0 "] =" AXzhz "; drOperate [" column1 "] = false; // Method2 drOperate [0] =" AXzhz "; drOperate [1] = false; // Method3 dt.Rows [0] [" column0 "] = "AXzhz"; dt.Rows [0] ["column1"] = false; // Method4 dt.Rows [0] [0] = "AXzhz"; dt.Rows [0] [1] = false; (8) EvaluateanotherDataTable'srowtocurrentDatatable dtOnlyScheme.Rows.Add (dt.Rows [0] .ItemArray); (9) Converttostring System.IO.StringWritersw = newSystem.IO.StringWriter (); System.Xml.XmlTextWriterxw = newSystem.Xml.XmlTextWriter ( ); dt.WriteXml (xw); strings = sw.ToString (); (10) FilterDataTable dt.DefaultView.RowFilter = "column1 <> true"; dt.DefaultView.RowFilter = "column1 = true"; (11) Sortrow dt.DefaultView.Sort = "ID, NameASC"; dt = dt.DefaultView.ToTable (); (12) BindDataTable // The default binding is actually DefaultView gvTestDataTable.DataSource = dt; gvTestDataTable.Dat  aBind (); (13) judgetheDataTable'sColumnnameisastring // Determine whether a string is the column name of the DataTable dtInfo.Columns.Contains ("AX"); (14) DataTableconverttoXMLandXMLconverttoDataTable protectedvoidPage_Load (objectsender, EventArgse) {DataTabledt_AX = newDataTable (); //dt_AX.Columns.Add("Sex",typeof(System.Boolean)); //DataRowdr=dt_AX.NewRow (); // dr ["Sex"] = true; //dt_AX.Rows.Add(dr ); stringxml = ConvertBetweenDataTableAndXML_AX (dt_AX); DataTabledt = ConvertBetweenDataTableAndXML_AX (xml);} publicstringConvertBetweenDataTableAndXML_AX (DataTabledtNeedCoveret) {System.IO.TextWritertw = newSystem.IO.StringWriter (); // ifTableName
 dtNeedCoveret.TableName = dtNeedCoveret.TableName.Length == 0? "Table_AX": dtNeedCoveret.TableName; dtNeedCoveret.WriteXml (tw); dtNeedCoveret.WriteXmlSchema (tw); returntw.ToString ();} PublicDataTableConvertBe { .TextReadertrDataTable = newSystem.IO.StringReader (xml.Substring (0, xml.IndexOf ("<? Xml"))); System.IO.TextReadertrSchema = newSystem.IO.StringReader (xml.Substring (xml.IndexOf ("< ? xml ")))); DataTabledtReturn = newDataTable (); dtReturn.ReadXmlSchema (trSchema); dtReturn.ReadXml (trDataTable); returndtReturn;}

Copy all or part of the datatable structure to a new datatable
datatable copy table structure: we can use the .clone () method;
DataTable oldDT = GetDataTable ();
DataTable newDT = oldDT.Clone ();
Copy all the information in the datatable to a new datatable, including the structure and data:
DataTable oldDT = GetDataTable ();
DataTable newDT = oldDT.Copy ();
Copy a row in the datatable: we can use the .ImportRow () method;
DataTable oldDT = GetDataTable ();
DataTable newDT = new DataTable ();
newDT.ImportRow (oldDT.Rows [1]); Copy the second row of data from the original datatable to the new datatable.

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?