Learn About DataTable In C#

Data Table is roughly equivalent to a table in a database. DataSet contains many Data Tables. It is a class and stores only one table. DataTable is an in-memory representation of a single database table which has the collection of columns and rows. It fetches only one row at a time. In DataTable, there is no unique key and foreign key constraints are available. In DataTable, the data source can’t be serialized.

DataTable

Get the data from the database and return as DataTable and create a new instance of DataTable.

  1. DataTable dtbranch1 = new DataTable();  
  2. dtbranch1 = ObjCom.methodName(Obj);  

dtbranch1

NoCreDeb
1

How can we change the column name of DataTable? If DataTable has more than one row, then change the column names.

  1. if (dtbranch1.Rows.Count > 0) {  
  2.     dtbranch1.Columns["Cre"].ColumnName = "CREDIT";  
  3.     dtbranch1.Columns["Deb"].ColumnName = "DEBIT";  
  4.     dtbranch1.AcceptChanges();  
  5. }  
NoCREDITDEBIT
1

How can we change the DataTypes? If we want to change the DataType of a column, then we should clone the DataTable and create a new instance of datatable, as shown below.

  1. dtbranch1.AcceptChanges();  
  2. DataTable dtbranch = dtbranch1.Clone();  
  3. dtbranch.Columns["CREDIT"].DataType = typeof(decimal);  
  4. dtbranch.Columns["DEBIT"].DataType = typeof(decimal);  
  5. foreach(DataRow row in dtbranch1.Rows) {  
  6.     dtbranch.ImportRow(row);  
NoCREDITDEBIT
1

Here is how to add the new columns and add one row in DataTable (Dynnamically Creating DataTable ):

  1. DataTable newdt2 = new DataTable();  
  2. DataRow newdr3 = null;  
  3. newdt2.Columns.Add("Number"typeof(string));  
  4. newdt2.Columns.Add("Name"typeof(decimal));  
  5. newdt2.Columns.Add("City"typeof(decimal));  
  6. newdr3 = newdt2.NewRow();  
  7. newdr3["Number "] = "1";  
  8. newdr3["Name "] = ViewState["NAME"];  
  9. newdr3["City "] = ViewState["CITY"];  
  10. newdt2.Rows.Add(newdr3);  

newdt2

NumberNameCity
1MuraliHyd

Here is how to merge the newdt2 Datatable with dtbranch datatable.

  1. dtbranch.Merge(newdt2);  

Accept all changes in DataTable.

  1. dtbranch.AcceptChanges();  
NoCREDITDEBITNumberNameCity
1

Print the DataTable in grid and if there is no record, then show an alert by using a server side alert message.

  1. if (dtbranch.Rows.Count > 0) {  
  2.     PartyGrid.DataSource = dtbranch;  
  3.     PartyGrid.DataBind();  
  4. else {  
  5.     ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "alertMessage""alert('No Record(s) Found')"true);  
  6.     //Label4.Text = "No Record(s) Found";  
  7. }  
  8. }  

PartyGrid

NoCREDITDEBITNumberNameCity
1
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now