Tuesday, June 28, 2011

Add Columns, Rows to a DataTable in C#


DataTable dt = new DataTable();
       
//Create an ID column for adding to the Datatable
DataColumn dcol = new DataColumn(CustomerID ,typeof(System.Int32));
dcol.AutoIncrement = true;
dt.Columns.Add(dcol);
//Create an ID column for adding to the Datatable
dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
  1. DataRow myNewRow;  
  2. 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.
  1. myNewRow["customerID"] = 1;   
Finally, we want to add this newly created row (with two columns) to the originally blank datatable we created in the beginning.
  1. dt.Rows.Add(myNewRow);  

No comments:

Post a Comment