Add Rows at runtime to Datagrid

21 09 2008


This document contains the sample code with explanation for adding rows to the datagrid at runtime using a button click event in .NET.


To add rows to the datagrid at runtime, the basic mechanism would be to add a dummy row to the dataset and then binding the same dataset to your Grid. After binding the dataset you need to control the behavior of the datagrid depending on your requirement by using it’s properties.

I will try to explain using a specific example.


We would be adding rows to the datagrid on a button click event with a requirement of having 5 rows on a one page and when you add the 6th row the control will be taken to second page.

One more thing when you add a row only last added row should be in Edit mode.

The code below shows a function that can be used to add blank rows to the first DataTable in any Dataset In this case, the first column in the Dataset that was used was a Primary Key and could not be blank, and I knew that the values from
the database would all be positive.

Code Snippet:

*****************************Code Begins***************************
‘Code below adds blank row and binds the datatable to the datagrid.
Private Sub add_rows()
querystring = “Your Query goes here”
cmdCodeMgmt.CommandText = querystring
daCodeMgmt.Fill(ds, “Table Name “)
dr = ds.Tables(0).NewRow
cnt = ds.Tables(0).Rows.Count
End Sub

*****************************Code Ends****************************