Add a row / Multiple rows to the data table c#.net

I suppose to use a data table as data source in my grid View controller. Can you please explain how I need to do it?

1. The first step is to create an empty Data Table.
DataTable dt = new DataTable();

2. Second step is to create a new DataRow object.
DataRow newRow = dt.NewRow();

3. Now you have created and initialized a DataRow. So then it is needed to add values to rows.
newRow["id"] = 1; // we have created column call “id” and add it to value 1
newRow["username"] = "adam" ; // we have created column call “username” and add it to value “adam”.

4. Next, we want to add this newly created row (with two columns) to the blank Datatable we created in the first step.

dt.Rows.Add(newRow);

5. You can now set this created Datatable as a DataSource and then DataBind to the GridView or any other similar C# control.

gridView1.Datasource = dt;
gridView1.Databind();

All the steps from above are put together in the below:

DataTable dt = new DataTable();
DataRow newRow = dt.NewRow();
newRow["id"] = 1;
newRow["username"] = "adam" ;
dt.Rows.Add(newRow);
gridView1.Datasource = dt;
gridView1.Databind();


Let see how to add multiple records in datatable without write multiple time code

DataTable dt = new DataTable();
dt.Columns.Add("Min", System.Type.GetType("System.Int32"));
dt.Columns.Add("Max", System.Type.GetType("System.Int32"));
dt.Columns.Add("Avg", System.Type.GetType("System.Int32"));

for (int i = 0; i < i =" i">
{
DataRow dr = dt.NewRow();
row["Min"] = i;
row["Max"] = i + 9;
row["Avg"] = (i + 9) / 2;
dt.Rows.Add(dr);
}

You can add values to row using for loop.










0 comments:

Post a Comment

Thank you very much