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.
- DataTable dtbranch1 = new DataTable();
- dtbranch1 = ObjCom.methodName(Obj);
dtbranch1
How can we change the column name of DataTable? If DataTable has more than one row, then change the column names.
- if (dtbranch1.Rows.Count > 0) {
- dtbranch1.Columns["Cre"].ColumnName = "CREDIT";
- dtbranch1.Columns["Deb"].ColumnName = "DEBIT";
- dtbranch1.AcceptChanges();
- }
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.
- dtbranch1.AcceptChanges();
- DataTable dtbranch = dtbranch1.Clone();
- dtbranch.Columns["CREDIT"].DataType = typeof(decimal);
- dtbranch.Columns["DEBIT"].DataType = typeof(decimal);
- foreach(DataRow row in dtbranch1.Rows) {
- dtbranch.ImportRow(row);
- }
Here is how to add the new columns and add one row in DataTable (Dynnamically Creating DataTable ):
- DataTable newdt2 = new DataTable();
- DataRow newdr3 = null;
- newdt2.Columns.Add("Number", typeof(string));
- newdt2.Columns.Add("Name", typeof(decimal));
- newdt2.Columns.Add("City", typeof(decimal));
- newdr3 = newdt2.NewRow();
- newdr3["Number "] = "1";
- newdr3["Name "] = ViewState["NAME"];
- newdr3["City "] = ViewState["CITY"];
- newdt2.Rows.Add(newdr3);
newdt2
Here is how to merge the newdt2 Datatable with dtbranch datatable.
Accept all changes in DataTable.
- dtbranch.AcceptChanges();
No | CREDIT | DEBIT | Number | Name | City |
1 |
Print the DataTable in grid and if there is no record, then show an alert by using a server side alert message.
- if (dtbranch.Rows.Count > 0) {
- PartyGrid.DataSource = dtbranch;
- PartyGrid.DataBind();
- } else {
- ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('No Record(s) Found')", true);
-
- }
- }
PartyGrid
No | CREDIT | DEBIT | Number | Name | City |
1 |