DataTable and Its Methods in
DataTable and Its Methods in
Net
DataTable
DataTable represents relational data into Tabular Form.
DataTable in C# is similar to the Tables in SQL.
ADO.NET provides a DataTable class to create and use
data table independently or we can get data from database
table in DataTable.
It can also be used with DataSet also.
Initially, when we create DataTable, it does not have table
schema (table structure).
We can create table schema by adding columns and
constraints to the table.
After defining table schema (table structure), we can add
rows to the table.
DataTable is a combination of DataColumn and DataRow.
We must include System.Data namespace before creating
DataTable.
Properties Of DataColumn in ADO.Net
Caption
DataType
AllowDBNull
MaxLength
PrimaryKey -> Property of DataTable
AutoIncrement
o AutoIncrementSeed -> Starting Value
DefaultValue
Unqiue
Source Code Of DataTable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace ADO_Net_DataTable
{
class Program
{
static void Main(string[] args)
{
try
{
DataTable employees = new DataTable("employees");
employees.Rows.Add(null,"Anum","Female");
employees.Rows.Add(null, "Zain", "Male");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
namespace Copy_Clone_DataTable
{
class Program
{
static void Main(string[] args)
{
try
{
string cs =
ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
string query = "select * from employee_tbl";
SqlDataAdapter sda = new SqlDataAdapter(query,con);
DataTable employees = new DataTable();
sda.Fill(employees);
Console.WriteLine("Clone DataTable");
if (CloneDataTable.Rows.Count > 0)
{
foreach (DataRow row in CloneDataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " "
+ row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
}
else
{
//Console.WriteLine("Rows Not Found..");
CloneDataTable.Rows.Add(1,"Asif","Male",25,13000,"Karachi");
CloneDataTable.Rows.Add(2, "Saba", "Female", 27, 23000,
"Sukkur");
}
foreach (DataRow row in CloneDataTable.Rows)
{
Console.WriteLine(row["id"] + " " + row["name"] + " " +
row["gender"] + " " + row["age"] + " " + row["salary"] + " " + row["city"]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}