How to Add New ASP.Net DataRow to DataTable
In ASP.Net, DataRow class provides the functionality to add a new row i.e. new record into the DataTable. DataRow object inherits the schema of ASP.Net DataTable and allows you to add the values for each DataColumn according to the specified DataType for a data column of DataTable. You can use the zero based index number of DataColumn or column name to pass the value for specific column in the new DataRow. Index of the DataColumn depends upon the order of adding a DataColumn to the DataTable. Consider the example of previous tutorial: Add ASP.Net DataColumn to a DataTable.
C# Code to Add New ASP.Net DataRow to DataTable
Example 1
Example to add DataColumn values using column Name:
// create a new row using NewRow() function of DataTable. // dataRow object will inherit the schema of myDataTable to create a new row DataRow dataRow = myDataTable.NewRow(); dataRow["firstName"] = "John"; dataRow["lastName"] = "Smith"; // add new data row to the data table. myDataTable.Rows.Add(dataRow); // similarly adds the second row to the DataTable dataRow = myDataTable.NewRow(); dataRow["firstName"] = "Will"; dataRow["lastName"] = "Smith"; myDataTable.Rows.Add(dataRow);
Example 2
Example to add DataColumn values using column index:
DataRow dataRow = myDataTable.NewRow(); dataRow[1] = "John"; dataRow[2] = "Smith"; myDataTable.Rows.Add(dataRow); dataRow = myDataTable.NewRow(); dataRow[1] = "Will"; dataRow[2] = "Smith"; myDataTable.Rows.Add(dataRow);
Note that in Example 2, column index 1 has been used for "firstName" column and 2 has been used for "lastName" because zero based index start from 0 as starting index for DataColumn of a DataTable. Here 0th index represents the index of the auto incrementing "auto_ID" column of the DataTable.
Continue to next tutorial: ASP.Net DataColumn Expression Property to learn how to specify an expression for data column to calculate its value based on formula or other data column values.
