Sri Lanka .NET 
       Forum Member

Friday, May 11, 2007

How to add columns and rows into a DataTable and then add this table into a DataSet.

This is qucik respond to one of my friends quiz, taht is how to add records to a table and then add this table into a dataset in Runtime.

Here is the C# code.

//Declaring Dataset and DataTable
DataSet ds = new DataSet("myDataset");
DataTable dt = new DataTable("myDataTable");


//Creating Datatable columns
dt.Columns.Add("ID", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));

//Datarow variable to use in adding rows
DataRow dr;


//Adding Rows
for(int i=0; i<10; i++)
{
dr = dt.NewRow();
dr["ID"] = i;
dr["Name"]=i.ToString();
dt.Rows.Add(dr);
}


//If you need to add the table in Dataset you can do like this
ds.Tables.Add(dt);

//Query the dataset.datatable to see the added values

foreach(DataRow r in ds.Tables[0].Rows)
{

//r[0] is the first columns. inseted r[0] you can use r["ID"]
Response.Write( r[0].ToString() + "-----" + r[1].ToString() + "<br>");
}

Labels:

0 Comments:

Post a Comment

<< Home