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
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
- <columns>
- <asp:BoundField HeaderText="RollNo" DataField="RollNo"/>
- <asp:BoundField HeaderText="Name" DataField="Name"/>
- <asp:BoundField HeaderText="Class" DataField="Class"/>
- </columns>
- </asp:GridView>
Step 2
On CS file ,Create the DataTable object. And add columns in it.
- DataTable GetTable()
- {
- DataTable table = new DataTable();
- table.Columns.Add("RollNo");
- table.Columns.Add("Name");
- table.Columns.Add("Class");
- return table;
- }
Step 3
On load event ,Bind datasource of gridview to datatable object created.
Code
- protected void Page_Load(object sender, EventArgs e)
- {
- DataTable dt = new DataTable();
- dt = GetTable();
- GridView1.DataSource = dt;
- GridView1.DataBind();
- }
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
- protected void Button1_Click(object sender, EventArgs e)
- {
- try
- {
- if (Session["table"] == null)
- {
- dt = GetTable();
- } else
- {
- dt = (DataTable) Session["table"];
- }
- dt.Rows.Add(txtRollNo.Text, txtName.Text, txtClass.Text);
- Session["table"] = dt;
- GridView1.DataSource = dt;
- GridView1.DataBind();
- txtClass.Text = "";
- txtName.Text = "";
- txtRollNo.Text = "";
- } catch (Exception ex) {}
- }