Here I have attached the source code of how to create Datatable objects and how to add datarow on that created datatable. For this I designed a form like the below screen shot.

- Create DataTable objects by declaring an
instance of the DataTable object.
Private DataTable CustomersTable = new DataTable(“Customers”);
- Then add the below code for create table
button click event
CustomersTable.Columns.Add(“CustomerID”);
CustomersTable.Columns.Add(“CompanyName”);
Like this you can add many columns to your table. Here I have created only two columns but you can create as per your requirement.
- Now after creating table we declared one
column as primary key so here I am going declared CustomerID as primary key
using this below code.
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0]=CustomersTable.Columns[“CustomerID”];
CustomersTable.PrimaryKey = keyColumns;
- Because primary key in not null that's why
we set CustomerID Columns to disallow Null values
CustomersTable.Columns[“CustomerID”].AllowDBNull = false;
- Now click on Add row button and add the
below code to button click event
DataRow CustRow = CustomersTable.NewRow();
Object[] CustRecord = {1,”Farukh”} ;
CustRow.ItemArray = CustRecord;
CustomersTable.Rows.Add(CustRow);
- Run the application and click button create table …..on your gridview table will be created and after click on add row button the datarow will be created.
Join the conversation! Your thoughts help the community grow.