When using a DataTable as a DataSource to a GridView in C#, it is often necessary to add additional rows, whether they be blank rows or fully populated rows, to the control. It has been my experience that it is much easier to add a DataRow into the DataTable prior to a DataBind.
The first step is to create an empty datatable. It would be perfectly legal to start with a datatable prepopulated with data. In this case, we are naming the Datatable, dt.
DataTable dt = new DataTable();
The next step is to create a new DataRow object. In this case, we are calling it “newRow”. The next step would be to initialize the DataRow object, which is the second line below:
DataRow myNewRow;
myNewRow = dt.NewRow();
Now that the DataRow has been created and initialized, simply add values to the object as you would an array. In the two examples below, we are adding values to two different columns in our row. We are first assigning the column with name customerId the integer value of 1. Secondly, we are assigning the column with name username a string johndoe. Repeat as needed.
myNewRow["customerId"] = 1;
myNewRow["username"] = “johndoe” ;
Finally, we want to add this newly created row (with two columns) to the originally blank datatable we created in the beginning.
dt.Rows.Add(myNewRow);
All the steps from above are put together in the example below:
DataTable dt = new DataTable();
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow["customerId"] = 1;
myNewRow["username"] = “johndoe” ;
dt.Rows.Add(myNewRow);
With that you can now set this datatable as a DataSource and DataBind a GridView or any other similar C# control.