25 November 2008

C# and ASP.NET Create Table Dynamically

In the run-time sometimes we have to create table dynamically.

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.

7 comments:

surekha said...

thank yuuu

techie said...

Thanks. This code has really help me

Anonymous said...

thanks!! great example :)

Vidhya said...

Nice Example....

Anonymous said...

How to bind data from database in datatable asp.netC#

Anonymous said...

Not Displaying anything at run time

Anonymous said...

how to copy a table at runtime