DataTable in ADO.NET

A DataTable in ADO.NET represents one table of in-memory relational data. Dot net developers can create DataTable objects by using DataAdapter object’s Fill or FillSchema methods within a DataSet. they also can create DataTable objects by ReadXml, ReadXmlSchema or InferXmlSchema methods of DataSet. after creating a DataTable object, we can add DataColumn objects to it and can specify a TableName.

A DataTable is a class of Disconnected architecture in the .NET Framework. It is found in the System.Data namespace and represents a single table. We can create a table and can add columns and rows of that table. Now, we will create an window application and use the DataTable class.

DataTable in ADO.Net

Syntax to create DataTable

DataTable dTable = new DataTable("NewTable");
Creating Columns in the DataTable
DataColumn dcObj = new DataColumn("Name of the column", datatype);
dTable.Columns.Add(dcObj);
dcObj.AutoIncrement = true;
dcObj.AutoIncrementSeed = 1;
dcObj.readonly = true;
dcObj.Unique = true;

Populate the DataTable using the DataRow object

Syntax

DataRow dRow ;
For(int i=0 ; i<5; ++i)
{
dRow = dTable.NewRow(); 
dRow["Name of Column"] = i + 1; 
dTable.Rows.Add(dRow); 
}

Modifying Row Data

AcceptChanges()

This method saves changes which made with records in a Datatable.

Syntax

dTable.Rows[2]["Name of Column"] = New value;
dTable.AcceptChanges();
Deleting Row
dTable.Rows[1].Delete();
dTable.AcceptChanges();

Clear() – This method clears (removes) all data from datatable

Clone() – The clone method copy the structure of Datatable. Means it copy only schema not full records of Datatable.

Copy() – The copy method copy the whole records with structure of Datatable.

Filtering data from DataTable

To filter records from the DataTable, use Select method and pass necessary filter expression.

Syntax

DataRow []rows = dTable.Select(filterCondition);
foreach( DataRow drow in rows )
{
dTable.Rows.Add(dRow.ItemArray);
}

 Sorting data of DataTable Using DataView

 Syntax

DataView dv = new DataView(dTable);
dv.Sort = "ColumnNameOfTable DESC";

Sorting data of DataTable Using DataTable.Select() method

Syntax

DataRow [] drow = dTable.Select("", "ColumnNameOfTable DESC");

 

Output

 

Demo Code

Download