Escolar Documentos
Profissional Documentos
Cultura Documentos
Introduction
DataTable is a central object in the ADO.NET library. If you are working with ADO.NET
- accessing data from database, you can not escape from DataTable. Other objects that
use DataTable are DataSet and DataView. In this tutorials, I will explain how to work
with DataTable. I have tried to cover most of the frequently used activity in the
DataTable, I hope you will like it.
Creating a DataTable
To create a DataTable, you need to use System.Data namespace, generally when you
create a new class or page, it is included by default by the Visual Studio. Lets write
following code to create a DataTable object. Here, I have pased a string as the DataTable
name while creating DataTable object.
// instantiate DataTable
To create column in the DataTable, you need to use DataColumn object. Instantiate the
DataColumn object and pass column name and its data type as parameter. Then call add
method of DataTable column and pass the DataColumn object as parameter.
dTable.Columns.Add(auto);
dTable.Columns.Add(name);
dTable.Columns.Add(address);
auto.AutoIncrement = true;
auto.AutoIncrementSeed = 1;
auto.ReadOnly = true;
If you want a particular column to be a unique column ie. you don't want duplicate
records into that column, then set its Unique property to true like below.
auto.Unique = true;
To set the primary key column in the DataTable, you need to create arrays of column and
store column you want as primary key for the DataTable and set its PrimaryKey property
to the column arrays. See the code below.
pK[0] = auto;
dTable.PrimaryKey = pK;
Till now we have created the DataTable, now lets populate the DataTable with some data.
Look at the code below, I have created a DataRow object above the loop and I am
assiging its value to the dTable.NewRow() inside the loop. After specifying columns
value, I am adding that row to the DataTable using dTable.Rows.Add method.
row = dTable.NewRow();
row["AutoID"] = i + 1;
dTable.Rows.Add(row);
Instead of using the column name, you can use ColumnIndex too, however it is not
suggested as you might want to add a column in the mid of the table then you will need to
change your code wherever you have specified the index of the column. Same applies
while reading or writing values into Database column.
In following code, I have specified the values of every column as the array separated by
comma (,) in the Add method of the dTable.Rows.
To edit the data of the row, sets its column value using row index or by specifying the
column name. In below example, I am updating the 3rd row of the DataTable as I have
specified the row index as 2 (dTable.Rows[2]).
dTable.Rows[2]["AutoID"] = 20;
dTable.Rows[2]["Name"] = "Modified";
dTable.AcceptChanges();
Deleting Row
// Delete row
dTable.Rows[1].Delete();
dTable.AcceptChanges();
To filter records from the DataTable, use Select method and pass necessary filter
expression. In below code, the 1st line will simply filter all rows whose AutoID value is
greater than 5. The 2nd line of the code filters the DataTable whose AutoID value is
greater than 5 after sorting it.
Note that Select method of the DataTable returns the array of rows that matche the filter
expression. If you want to loop through all the filtered rows, you can use foreach loop as
shown below. In this code, I am adding all the filtered rows into another DataTable.
dTable1.Rows.Add(thisRow.ItemArray);
We can use almost all aggregate functions with DataTable, however the syntax is bit
different than standard SQL.
Suppose we need to get the maximum value of a particular column, we can get it in the
following way.
DataRow[] rows22 = dTable.Select("AutoID = max(AutoID)");
To get the sum of a particular column, we can use Compute method of the DataTable.
Compute method of the DataTable takes two argument. The first argument is the
expression to compute and second is the filter to limit the rows that evaluate in the
expression. If we don't want any filteration (if we need only the sum of the AutoID
column for all rows), we can leave the second parameter as blank ("").
Oops !. There is no direct way of sorting DataTable rows like filtering (Select method to
filter DataRows).
Using DataView
See the code below. I have created a DataView object by passing my DataTable as
parameter, so my DataView will have all the data of the DataTable. Now, simply call the
Sort method of the DataView and pass the sort expression. Your DataView object have
sorted records now, You can either directly specify the Source of the Data controls object
like GridView, DataList to bind the data or if you need to loop through its data you can
use ForEach loop as below.
// Sorting DataTable
Response.Write(view["Address"].ToString());
}
Using DataTable.Select() method
Yes, you can sort all the rows using Select method too provided you have not specified
any filter expression. If you will specify the filter expression, ofcourse your rows will be
sorted but filter will also be applied. A small drawback of this way of sorting is that it will
return array of DataRows as descibed earlier so if you are planning to bind it to the Data
controls like GridView or DataList you will have for form a DataTable by looping
through because directly binding arrays of rows to the Data controls will not give desired
results.
If you need XmlSchema of the DataTabe, you can use WriteXmlSchema to write and
ReadXmlSchema to read it. There are several overloads methods of both methods and
you can pass filename, stream, TextReader, XmlReader etc. as the parameter. In this code,
the schema will be written to the .xml file and will be read from there.
dTable.WriteXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
dTableXmlSchema.ReadXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
If you have a scenario, where you need to write the data of the DataTable into xml
format, you can use WriteXml method of the DataTable. Note that WriteXml method will
not work if you will not specify the name of the DataTable object while creating it. Look
at the first code block above, I have passed "Dynamically_Generated" string while
creating the instance of the DataTable. If you will not specify the name of the DataTable
then you will get error as WriteXml method will not be able to serialize the data without
it.
// Also if you are planning to read back this XML into DataTable, you
should define the XmlWriteMode.WriteSchema too
dTableXml.ReadXml(Server.MapPath("~/DataTable.xml"));
If you are planning to read the xml you have just created into the DataTable sometime
later then you need to specify XmlWriteMode.WriteSchema too as the 2nd parameter
while calling WriteXml method of the DataTable otherwise normally WriteXml method
doesn't write schema of the DataTable. In the abscence of the schema, you will get error
(DataTable does not support schema inference from Xml) while calling ReadXml method
of the DataTable.