ASP.NET - to create dynamic datatable with 5 columns & 3 rows

Asked By anbu n on 02-Nov-11 12:52 PM

need to create dynamic datatable with 5 columns & 3 rows


smr replied to anbu n on 02-Nov-11 12:59 PM
hi

From the namespace System.Data DataTable DataColumn classes we can easily create table dynamically in C# and also in ASP.NET.



using System.Data;
 
// Create a DataTable instance
DataTable dTbl = new DataTable("myDynamicTable");
 
// Create a DataColumn instances
 
DataColumn dValue = new DataColumn();
DataColumn dMember = new DataColumn();
 
dValue.ColumnName = "Id";
dValue.DataType = Type.GetType("System.Int32");
 
dMember.ColumnName = "Name";
dMember.DataType = Type.GetType("System.String");
 
// Add these DataColumns into the DataTable
 
dTbl.Columns.Add(dValue);
dTbl.Columns.Add(dMember);

After you create table dynamically, you can add rows into it.
It is a good way to create DataRow from the table we create, with the function NewRow().
// Create a DataRow Instance from the table we create above, with NewRow();
 
DataRow myrow = dTbl.NewRow();
 
myrow["Id"] = 1;
myrow["Name"] = "Tux";
 
// Add the row into the table
 
dTbl.Rows.Add(myrow);

That's all
for creating table dynamically in C# and also ASP.NET.


refer
http://alperguc.blogspot.com/2008/11/c-and-aspnet-create-table-dynamically.html
aneesa replied to anbu n on 02-Nov-11 01:17 PM
DataTable dt=new DataTable();
dt.columns.Add("Col1",typeof(system.string));
dt.columns.Add("Col2",typeof(system.string));
dt.columns.Add("Col3",typeof(system.string));
dt.columns.Add("Col4",typeof(system.string));
dt.columns.Add("Col5",typeof(system.string));
dt.Rows.Add("A","B","C","D","E");
dt.Rows.Add("F","G","C","D","E");
dt.Rows.Add("H","I","C","D","E");
dipa ahuja replied to anbu n on 02-Nov-11 02:00 PM
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    DataTable dt = new DataTable();
 
    //Adding columns
 
    dt.Columns.Add("Names"typeof(string));
    dt.Columns.Add("ID"typeof(int));
    //same way add other threee columns 
    
    //Adding Row
 
    dt.Rows.Add("dipa",1);
    dt.Rows.Add("sita",2);
    dt.Rows.Add("priya", 3);
  }
}