Dynamically Adding and Deleting Rows in GridView and Saving All Rows at Once

In this blog, I’m going to wrap up everything into one for easy reference. The following are the main features that you will see for this entire post:
  • Adding rows of TextBox and DropDownlist
  • Retain TextBox values and DropDownList selected values across postbacks
  • Ability to remove rows
  • Save all values at once 
To get started fire up Visual Studio and then add a new WebForm page. Add a GridView control to the page. Here’s the GridView HTML markup:
  1. <asp:gridview ID="Gridview1"  runat="server"  ShowFooter="true"                              AutoGenerateColumns="false"                              OnRowCreated="Gridview1_RowCreated">  
  2.     <Columns>  
  3.         <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />  
  4.         <asp:TemplateField HeaderText="Header 1">  
  5.             <ItemTemplate>  
  6.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  7.             </ItemTemplate>  
  8.         </asp:TemplateField>  
  9.         <asp:TemplateField HeaderText="Header 2">  
  10.             <ItemTemplate>  
  11.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  12.             </ItemTemplate>  
  13.         </asp:TemplateField>  
  14.         <asp:TemplateField  HeaderText="Header 3">  
  15.             <ItemTemplate>  
  16.                 <asp:DropDownList ID="DropDownList1" runat="server"                                           AppendDataBoundItems="true">  
  17.                     <asp:ListItem Value="-1">Select</asp:ListItem>  
  18.                 </asp:DropDownList>  
  19.             </ItemTemplate>  
  20.         </asp:TemplateField>  
  21.         <asp:TemplateField HeaderText="Header 4">  
  22.             <ItemTemplate>  
  23.                 <asp:DropDownList ID="DropDownList2" runat="server"                                           AppendDataBoundItems="true">  
  24.                     <asp:ListItem Value="-1">Select</asp:ListItem>  
  25.                 </asp:DropDownList>  
  26.             </ItemTemplate>  
  27.             <FooterStyle HorizontalAlign="Right" />  
  28.             <FooterTemplate>  
  29.                 <asp:Button ID="ButtonAdd" runat="server"                                       Text="Add New Row"                                       onclick="ButtonAdd_Click" />  
  30.             </FooterTemplate>  
  31.         </asp:TemplateField>  
  32.         <asp:TemplateField>  
  33.             <ItemTemplate>  
  34.                 <asp:LinkButton ID="LinkButton1" runat="server"                                          onclick="LinkButton1_Click">Remove</asp:LinkButton>  
  35.             </ItemTemplate>  
  36.         </asp:TemplateField>  
  37.     </Columns>  
  38. </asp:gridview>  

As you can see from the markup above, I have setup a BoundField for displaying the RowNumber and some TemplateField columns so that GridView will automatically generate a row of TextBox and DropDownLists when adding a new row. You will also see that I have added a Button Control under the FooterTemplate at the last DropDownList column and a LinkButton at the last column in the GridView for removing rows.

Note: Since we added a control at the GridView footer, then be sure to set ShowFooter to TRUE in the GridView.

CODE BEHIND

Just for the simplicity of the demo, I’m just going to create a dummy data using ArrayList as the data source for our DropDownLists. In real scenario you may query your database and bind it to your DropDownList. Here are the full codes below:

  1. using System;  
  2. using System.Collections;  
  3. using System.Data;  
  4. using System.Web.UI;  
  5. using System.Web.UI.WebControls;  
  6. namespace WebFormsDemo {  
  7.     public partial class DynamicGrid: System.Web.UI.Page {  
  8.         private ArrayList GetDummyData() {  
  9.             ArrayList arr = new ArrayList();  
  10.             arr.Add(new ListItem("Item1""1"));  
  11.             arr.Add(new ListItem("Item2""2"));  
  12.             arr.Add(new ListItem("Item3""3"));  
  13.             arr.Add(new ListItem("Item4""4"));  
  14.             arr.Add(new ListItem("Item5""5"));  
  15.             return arr;  
  16.         }  
  17.         private void FillDropDownList(DropDownList ddl) {  
  18.             ArrayList arr = GetDummyData();  
  19.             foreach(ListItem item in arr) {  
  20.                 ddl.Items.Add(item);  
  21.             }  
  22.         }  
  23.         private void SetInitialRow() {  
  24.             DataTable dt = new DataTable();  
  25.             DataRow dr = null;  
  26.             dt.Columns.Add(new DataColumn("RowNumber"typeof(string)));  
  27.             dt.Columns.Add(new DataColumn("Column1"typeof(string)));  
  28.             for TextBox value dt.Columns.Add(new DataColumn("Column2"typeof(string)));  
  29.             for TextBox value dt.Columns.Add(new DataColumn("Column3"typeof(string)));  
  30.             for DropDownList selected item dt.Columns.Add(new DataColumn("Column4"typeof(string)));  
  31.             for DropDownList selected item dr = dt.NewRow();  
  32.             dr["RowNumber"] = 1;  
  33.             dr["Column1"] = string.Empty;  
  34.             dr["Column2"] = string.Empty;  
  35.             dt.Rows.Add(dr);  
  36.             Store the DataTable in ViewState  
  37.             for future reference ViewState["CurrentTable"] = dt;  
  38.             Bind the Gridview Gridview1.DataSource = dt;  
  39.             Gridview1.DataBind();  
  40.             After binding the gridview, we can then extract and fill the DropDownList with Data DropDownList ddl1 = (DropDownList) Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");  
  41.             DropDownList ddl2 = (DropDownList) Gridview1.Rows[0].Cells[4].FindControl("DropDownList2");  
  42.             FillDropDownList(ddl1);  
  43.             FillDropDownList(ddl2);  
  44.         }  
  45.         private void AddNewRowToGrid() {  
  46.             if (ViewState["CurrentTable"] != null) {  
  47.                 DataTable dtCurrentTable = (DataTable) ViewState["CurrentTable"];  
  48.                 DataRow drCurrentRow = null;  
  49.                 if (dtCurrentTable.Rows.Count > 0) {  
  50.                     drCurrentRow = dtCurrentTable.NewRow();  
  51.                     drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;  
  52.                     add new row to DataTable dtCurrentTable.Rows.Add(drCurrentRow);  
  53.                     Store the current data to ViewState  
  54.                     for future reference ViewState["CurrentTable"] = dtCurrentTable;  
  55.                     for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++) {  
  56.                         extract the TextBox values TextBox box1 = (TextBox) Gridview1.Rows[i].Cells[1].FindControl("TextBox1");  
  57.                         TextBox box2 = (TextBox) Gridview1.Rows[i].Cells[2].FindControl("TextBox2");  
  58.                         dtCurrentTable.Rows[i]["Column1"] = box1.Text;  
  59.                         dtCurrentTable.Rows[i]["Column2"] = box2.Text;  
  60.                         extract the DropDownList Selected Items DropDownList ddl1 = (DropDownList) Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");  
  61.                         DropDownList ddl2 = (DropDownList) Gridview1.Rows[i].Cells[4].FindControl("DropDownList2");  
  62.                         Update the DataRow with the DDL Selected Items dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;  
  63.                         dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text;  
  64.                     }  
  65.                     Rebind the Grid with the current data to reflect changes Gridview1.DataSource = dtCurrentTable;  
  66.                     Gridview1.DataBind();  
  67.                 }  
  68.             } else {  
  69.                 Response.Write("ViewStateull");  
  70.             }  
  71.             Set Previous Data on Postbacks SetPreviousData();  
  72.         }  
  73.         private void SetPreviousData() {  
  74.             int rowIndex = 0;  
  75.             if (ViewState["CurrentTable"] != null) {  
  76.                 DataTable dt = (DataTable) ViewState["CurrentTable"];  
  77.                 if (dt.Rows.Count > 0) {  
  78.                     for (int i = 0; i < dt.Rows.Count; i++) {  
  79.                         TextBox box1 = (TextBox) Gridview1.Rows[i].Cells[1].FindControl("TextBox1");  
  80.                         TextBox box2 = (TextBox) Gridview1.Rows[i].Cells[2].FindControl("TextBox2");  
  81.                         DropDownList ddl1 = (DropDownList) Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");  
  82.                         DropDownList ddl2 = (DropDownList) Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");  
  83.                         Fill the DropDownList with Data FillDropDownList(ddl1);  
  84.                         FillDropDownList(ddl2);  
  85.                         if (i < dt.Rows.Count - 1) {  
  86.                             Assign the value from DataTable to the TextBox box1.Text = dt.Rows[i]["Column1"].ToString();  
  87.                             box2.Text = dt.Rows[i]["Column2"].ToString();  
  88.                             Set the Previous Selected Items on Each DropDownList on Postbacks ddl1.ClearSelection();  
  89.                             ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;  
  90.                             ddl2.ClearSelection();  
  91.                             ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true;  
  92.                         }  
  93.                         rowIndex++;  
  94.                     }  
  95.                 }  
  96.             }  
  97.         }  
  98.         protected void Page_Load(object sender, EventArgs e) {  
  99.             if (!Page.IsPostBack) {  
  100.                 SetInitialRow();  
  101.             }  
  102.         }  
  103.         protected void ButtonAdd_Click(object sender, EventArgs e) {  
  104.             AddNewRowToGrid();  
  105.         }  
  106.         protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e) {  
  107.             if (e.Row.RowType == DataControlRowType.DataRow) {  
  108.                 DataTable dt = (DataTable) ViewState["CurrentTable"];  
  109.                 LinkButton lb = (LinkButton) e.Row.FindControl("LinkButton1");  
  110.                 if (lb != null) {  
  111.                     if (dt.Rows.Count > 1) {  
  112.                         if (e.Row.RowIndex == dt.Rows.Count - 1) {  
  113.                             lb.Visible = false;  
  114.                         }  
  115.                     } else {  
  116.                         lb.Visible = false;  
  117.                     }  
  118.                 }  
  119.             }  
  120.         }  
  121.         protected void LinkButton1_Click(object sender, EventArgs e) {  
  122.             LinkButton lb = (LinkButton) sender;  
  123.             GridViewRow gvRow = (GridViewRow) lb.NamingContainer;  
  124.             int rowID = gvRow.RowIndex;  
  125.             if (ViewState["CurrentTable"] != null) {  
  126.                 DataTable dt = (DataTable) ViewState["CurrentTable"];  
  127.                 if (dt.Rows.Count > 1) {  
  128.                     if (gvRow.RowIndex < dt.Rows.Count - 1) {  
  129.                         Remove the Selected Row data and reset row number dt.Rows.Remove(dt.Rows[rowID]);  
  130.                         ResetRowID(dt);  
  131.                     }  
  132.                 }  
  133.                 Store the current data in ViewState  
  134.                 for future reference ViewState["CurrentTable"] = dt;  
  135.                 Re bind the GridView  
  136.                 for the updated data Gridview1.DataSource = dt;  
  137.                 Gridview1.DataBind();  
  138.             }  
  139.             Set Previous Data on Postbacks SetPreviousData();  
  140.         }  
  141.         private void ResetRowID(DataTable dt) {  
  142.             int rowNumber = 1;  
  143.             if (dt.Rows.Count > 0) {  
  144.                 foreach(DataRow row in dt.Rows) {  
  145.                     row[0] = rowNumber;  
  146.                     rowNumber++;  
  147.                 }  
  148.             }  
  149.         }  
  150.     }