Adding Rows to GridView on Button Click Event at Client Side

I would like to share code snippet cum tutorial for adding rows in gridview at client side on button click event using datatable, session and ajax.The user need to enter values in textboxes for fields, that get added as a row in gridview.

Step 1

Add gridview on form. Set AutoGenerateColumns to false. Add three boundfields. (In this example we will store student information(RollNo,Name,Class) )

Code

  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">  
  2.     <columns>  
  3.         <asp:BoundField HeaderText="RollNo" DataField="RollNo"/>  
  4.         <asp:BoundField HeaderText="Name" DataField="Name"/>  
  5.         <asp:BoundField HeaderText="Class" DataField="Class"/>  
  6.     </columns>  
  7. </asp:GridView> 

Step 2

On CS file ,Create the DataTable object. And add columns in it.

  1. DataTable GetTable()  
  2. {  
  3.     DataTable table = new DataTable();  
  4.     table.Columns.Add("RollNo");  
  5.     table.Columns.Add("Name");  
  6.     table.Columns.Add("Class");  
  7.     return table;  
  8. }  

Step 3

On load event ,Bind datasource of gridview to datatable object created.

Code

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     DataTable dt = new DataTable();  
  4.     dt = GetTable();  
  5.     GridView1.DataSource = dt;  
  6.     GridView1.DataBind();  
  7. }  

Step 4

On button click event. Add a row to datatable object. And Store datable object in session or ViewState ,assign datasource of gridview to datatable object.

Code

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     try  
  4.     {  
  5.         if (Session["table"] == null)  
  6.         {  
  7.             dt = GetTable();  
  8.         } else  
  9.         {  
  10.             dt = (DataTable) Session["table"];  
  11.         }  
  12.         dt.Rows.Add(txtRollNo.Text, txtName.Text, txtClass.Text);  
  13.         Session["table"] = dt;  
  14.         GridView1.DataSource = dt;  
  15.         GridView1.DataBind();  
  16.         txtClass.Text = "";  
  17.         txtName.Text = "";  
  18.         txtRollNo.Text = "";  
  19.     } catch (Exception ex) {}  
  20. }