Introduction
The DataTable is an in-memory representation of a table including columns, rows, and unique and foreign key constraints. It is used for working with and saving data in the data source in a disconnected environment. The DataTable objects can work with any of the data providers.
Properties, Methods and Events of DataTable Class
- Constraints - This property retrieves constraints of the current table.
- DefaultView - This property retrieves a customized view of the table that includes a filtered view, or a cursor position.
- Locale - This property only retrieves the locale details and information for comparing strings in the table.
- PrimaryKey - This property specifies or retrieves primary key columns.
- GetErrors - This method retrieves an array of DataRow objects having errors.
- ImportRow - This method copies the specified DataRow into a DataTable along with its property settings, original and current values.
- Merge - This method merges the specified DataTable with the present DataTable.
- RejectChanges - This method discards or rejects all the changes made to the table since it was loaded or since the last time the AcceptChanges() method was called.
- TableCleared - Event occurs after a DataTable is cleared.
Source code demonstrates how to use the DataTable object along with the SqlCommandBuilder class to add a new column and row into a table of the database.
- SqlConnection sqlconAirspeed=new SqlConnection(“Data source=MYDATA\\SQLEXPRESS; Initial Catalog=Airspeed; Integrated Security="SSIP”);
- SqlDataAdapter sqldaAirSpeed=new SqlDataAdapter(“SELECT * FROM Employee”, sqlconAirspeed);
- SqlCommandBuilder sqlcombEmployee=new SqlCommandBuilder(sqldaAirSpeed);
- DataSet dsetAirSpeed=new DataSet();
- sqldaAirSpeed.Fill(dsetAirSpeed,”Employee”);
- DataGridView dgvwEmployee=new DataGridView();
- DataTable dtableEmployee=dsetAirSpeed.Tables(“Employee”);
- DataColumn[] dcolKey=new DataColumn[1];
- dcolKey[0]=dtableEmployee.Columns[“EmpID”];
- dtableEmployee.PrimaryKey=dcolKey;
- DataRow drowEmployee=dsetAirSpeed.Tables[“Employee”].NewRow();
- drowEmployee[0]=”A001”;
- drowEmployee[1]=”Ashish”;
- drowEmployee[2]=”3432-432-7438”;
- dtableEmployee.Rows.Add[drowEmployee);
- sqldaAirSpeed.Update(dtableEmployee);
- dgvwEmployee.DataSource=dvwEmployee.Table;
- dgvwEmployee.Sort=EName DESC”;
In this code, the SqlDataAdapter object is passed to the constructor of SqlCommandBuilder class. This class generates commands to update the table with the changes, made to the DataSet. The DataSet is filled with the records of Employee table . An instance of the DataTable class is created and is populated with the records of Employee table. An array object of the DataColumn class is created and refers to the EmpID column of the Employee table. This column is set as the primary key in the DataSet by using the PrimaryKey Property. A new row is added to the table in the DataSet using the NewRow() method. Finally , the new row is added to the table using the Update() method of SqlDataAdapter class. The DataGridView control is used to display the records of the table in descending order of employee names. This is specified using the Sort property of DataGridView class.
DataTableCollection Class
The DataTableCollection class consists of a collection of tables used by the object of the DataSet class. The DataTableCollection object can be accessed by using the Tables property of the DataSet class. The class manages the tables using the Add(), Remove() and Clear() methods.
Following are the properties, methods and events of DataTableCollection class.
- IsReadOnly - This property retrieves a value that indicates whether the InternalDataCollectionBase class is read-only.
- AddRange - This method copies the DataTable elements to the end of the collection.
- IndexOf - This method retrieves the index in the DataTable object collection.
- RemoveAt - This method removes the DataTable object from the specific index in the collection.
- CollectionChanging - This event occurs when the DataTable objects are added or removed in the DataTableCollection.
Source code demonstrate how to retrieve the table names existing in the DataTableCollection object.
- SqlConnection sqlconABMotors = new SqlConnection(“Data Source = MYDATA\\ SQLEXPRESS; Initial Catalog = ABMotors; Integrated Security = SSIP”);
- SqlDataAdapter sqldaABMotors = new SqlDataAdapter(“SELECT * FROM TwoWheeler”, sqlconABMotors);
- DataSet dsetABMotors = new DataSet();
- sqldaABMotors.Fill(dsetABMotors, ”FourWheeler”);
- ListBox lstIndex = new ListBox();
- DataTableCollection dtableCollection = dsetABMotors.Tables;
- foreach(DataTable dtableIndex in dtableCollection) {
- lstIndex.Items.Add(dtableIndex.TableName);
- }
In this source code, the DataSet object is filled with the records of two tables namely, TwoWheeler and FourWheeler. The DataTableCollection object refers
to these tables. This is done by using the Tables property of the DataSet . All the tables existing in the collection are added to the ListBox using the ForEach loop and the TableName property of the DataTable class.
Setting Relation between Tables
A DataRelation object can be used to automatically generated and apply a ForeignKeyConstraint or to navigate through records or tables. The DataRelation object allows users to navigate through both parent and child records of the related tables even in the disconnected architecture. For example, if a parent row is selected, the DataRelation object can be used to retrieve its child rows.
Source code below demonstrate how to display two related tables
- SqlConnection sqlAutomobileInverntory=new SqlConnection(“Data Source=MYDATA\\SQLEXPRESS;Initial Catalog=AutomobileInventory;Integrated Security=SSIP”);
- DataSet dsetAutomobileInventory=new DataSet();
- SqlDataAdapter sqldaAutomobileInventory=new SqlDataAdapter(“SELECT * FROM Customers”, sqlconAutomobileInventory);
- sqldaAutomobileInventory.Fill(dsetAutomobileInventory,”Customers”);
- sqldaAutomobileInventory=new SqlDataAdapter(“SELECT * from Orders”,sqlconAutomobileInventory);
- sqldaAutomobileInventory.Fill(dsetAutomobileInventory,”Orders”);
- DataColumn dcolParCol=dsetAutomobileInventory.Tables[“Customers”].Columns[“CustomerID”];
- DataColumn dcolChiCol=dsetAutomobileInventory.Tables[“Orders”].Columns[“CustomerID”];
- DataRelation drelCustomer=new DataRelation(“CustRelation”,dcolParCol,dcolChicol);
- dsetAutomobileInventory.Relations.Add(drelCustomer);
- DataGrid dgridCustomers=new DataGrid();
- dgridCustomers.Size=new Size(300,300);
- dgridCustomers.DataSource=dsetAutomobileInventory.Tables(“Customers”);
In this source code, the DataSet object is filled with records of Customers and Orders table. Two instances of the DataColumn calss are created , which refers to the common column in both the tables. An instance of the DataRelation class is created . The Constructor of this class takes the name of the relation and the two DataColumn objects as the parameter. The Relations property is used to add the relation in the DataSet. The DataGrid control is used to display the related tables in a tabular format. This is done by linking the control to the DataSet using the DataSource property of the DataGrid class.
Summary
The DataTable is an in-memory representation of a table including columns, rows, and unique and foreign key constraints. The DataTableCollection class consists of a collection of tables used by the object of the DataSet class. A DataRelation object can be used to automatically generated and apply a ForeignKeyConstraint or to navigate through records or tables.