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

A few years ago I wrote a series of articles showing how to add dynamic textboxes, dynamic dropdownlists and a combination of both controls in a GridView control. I've posted another couple of posts about how to delete rows for dynamically created rows and how to save them all at once. You can find the series of articles here: ASP.NET and Dynamic Controls.

In this article, I'm going to wrap up everything into one for easy reference. The following are the main features that you will see:

  • 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:

ASPX Markup

  1. <asp:gridview ID="Gridview1"  runat="server"  ShowFooter="true"  
  2.                              AutoGenerateColumns="false"  
  3.                              OnRowCreated="Gridview1_RowCreated">  
  4.     <Columns>  
  5.         <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />  
  6.         <asp:TemplateField HeaderText="Header 1">  
  7.             <ItemTemplate>  
  8.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  9.             </ItemTemplate>  
  10.         </asp:TemplateField>  
  11.         <asp:TemplateField HeaderText="Header 2">  
  12.             <ItemTemplate>  
  13.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  14.             </ItemTemplate>  
  15.         </asp:TemplateField>  
  16.         <asp:TemplateField  HeaderText="Header 3">  
  17.             <ItemTemplate>  
  18.                 <asp:DropDownList ID="DropDownList1" runat="server"  
  19.                                           AppendDataBoundItems="true">  
  20.                     <asp:ListItem Value="-1">Select</asp:ListItem>  
  21.                 </asp:DropDownList>  
  22.             </ItemTemplate>  
  23.         </asp:TemplateField>  
  24.         <asp:TemplateField HeaderText="Header 4">  
  25.             <ItemTemplate>  
  26.                 <asp:DropDownList ID="DropDownList2" runat="server"  
  27.                                           AppendDataBoundItems="true">  
  28.                     <asp:ListItem Value="-1">Select</asp:ListItem>  
  29.                 </asp:DropDownList>  
  30.             </ItemTemplate>  
  31.             <FooterStyle HorizontalAlign="Right" />  
  32.             <FooterTemplate>  
  33.                 <asp:Button ID="ButtonAdd" runat="server"   
  34.                                      Text="Add New Row"   
  35.                                      onclick="ButtonAdd_Click" />  
  36.             </FooterTemplate>  
  37.         </asp:TemplateField>  
  38.         <asp:TemplateField>  
  39.             <ItemTemplate>  
  40.                 <asp:LinkButton ID="LinkButton1" runat="server"   
  41.                                         onclick="LinkButton1_Click">Remove</asp:LinkButton>  
  42.             </ItemTemplate>  
  43.         </asp:TemplateField>  
  44.     </Columns>  
  45. </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 the GridView will automatically generate a row of TextBoxes 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 creating a dummy data using ArrayList as the data source for our DropDownLists. In a real scenario you may query your database and bind it to your DropDownList. Here is the full code:

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

Method Definitions

  • GetDummyData(): A method that returns an ArrayList. Basically this method contains a static dummy data for populating the DropDownList. You may want to use a database when dealing with real world scenarios.

  • FillDropDownList(DropDownList ddl): A method that fills the DropDownList with the dummy data.

  • SetInitialRow(): A method that binds the GridView on initial load with a single row of data. The DataTable defined in this method is stored in ViewState so that it can be referenced anywhere in the code across postbacks. Basically this table will serve as the original DataSource for the GridView. Keep in mind that this is just for demo, so be careful when using ViewState to avoid page performance issue. Also ViewState has a limit when it comes to size so make sure that you don't store a huge amount of data in it.

  • AddNewRowToGrid(): A method that adds a new row to the GridView when a Button is clicked and store the newly added row values in the Original Table that was defined in the SetInitialRow() method.

  • SetPreviousData(): A method that retains all the items that was selected from the DropDownList and TextBox when it postbacks.

  • ResetRowID(): A method that refreshes the grid's row number when a row is deleted.

The Events

  • ButtonAdd_ Click: Calls then AddNewRowToGrid() method.

  • LinkButto1_Click: This method will be invoked once the “remove” link is clicked from the grid. This is where the data from the data source will be remove based on the row index , reset the row number afterwards and finally store the updated data source in ViewState again and bind it to the grid to reflect the changes.

  • Gridview1_RowCreated: This is where we put the basic validation in GridView for not allowing users to see the “remove” button in the last row.

The Output

Running the page will display something like this in the browser.

On Initial load:

After adding a new row:



Removing a row:



After removing a row:



That's it! Now the next thing that you guys might be asking is how to save the data in the database. Well, don't worry, because in the next step I'm going to show you how.

Saving All Data at Once

The first thing to do is you need to create a database and a table for storing the data. So fire up SQL Management Studio or the Express version of SQL Server and create the table below with the following fields.

Save the table to whatever you like but for this demo I named the table as “GridViewDynamicRow”.

Note: I set the RowID to auto increment so that the id will be automatically generated for every new added row in the table. To do this select the Column name “RowID” and in the column properties set the “Identity Specification” to yes.

Once you've created the table then switch back to Visual Studio and add a Button control to the form.

For example:

  1. <asp:Button ID="BtnSave" runat="server" Text="Save All" OnClick="BtnSave_Click" />  

Now let's create the method for saving the data to the database. The first thing we need here is to set up the connection string so that we can communicate with our database from our code. For this example we will use the web.config file for setting up the connection string. See the markup below:

  1. <connectionStrings>  
  2.    <add name="DBConnection" connectionString="Data Source=win-   ehm93ap21cf\SQLEXPRESS;Initial Catalog=DemoDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>   
  3. </connectionStrings>  

We can now proceed to creating the method for saving the data to the database. First, add the following namespaces below:

  1. using System.Collections.Specialized;  
  2. using System.Text;  
  3. using System.Data.SqlClient;  

We need to declare the namespaces above so that we can use the SqlClient, StrngCollections and StringBuilder built-in methods in our code later.

Second, create the method for calling the connection string that was setup from the web.config file.

  1. private string GetConnectionString()   
  2. {  
  3.    return ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;  
  4. }  

And here's the code block for inserting all the rows into our database:

  1. private void InsertRecords(StringCollection sc)   
  2. {  
  3.     StringBuilder sb = new StringBuilder(string.Empty);  
  4.     string[] splitItems = null;  
  5.     const string sqlStatement = "INSERT INTO GridViewDynamicData (Field1,Field2,Field3,Field4) VALUES";  
  6.     foreach(string item in sc)   
  7.     {  
  8.         if (item.Contains(","))   
  9.         {  
  10.             splitItems = item.Split(",".ToCharArray());  
  11.             sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);  
  12.         }  
  13.     }  
  14.   
  15.     using(SqlConnection connection = new SqlConnection(GetConnectionString()))   
  16.     {  
  17.         connection.Open();  
  18.         using(SqlCommand cmd = new SqlCommand(sb.ToString(), connection))   
  19.         {  
  20.             cmd.CommandType = CommandType.Text;  
  21.             cmd.ExecuteNonQuery();  
  22.         }  
  23.     }  
  24.     lblMessage.Text = "Records successfully saved!";  
  25. }  

The InsertRecords() method takes a StringCollection object as the parameter. The StringCollection object holds all the values from the dynamic grid. We then split the values from the collection and then create a SQL query for each row using StringBuilder. Then we then make a connection to the database and then execute the query for inserting the data.

Finally, here is the code block for the Button click event:

  1. protected void BtnSave_Click(object sender, EventArgs e)   
  2. {  
  3.     int rowIndex = 0;  
  4.     StringCollection sc = new StringCollection();  
  5.     if (ViewState["CurrentTable"] != null)   
  6.     {  
  7.         DataTable dtCurrentTable = (DataTable) ViewState["CurrentTable"];  
  8.         if (dtCurrentTable.Rows.Count > 0)   
  9.         {  
  10.             for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)  
  11.             {  
  12.                 //extract the TextBox values  
  13.                 TextBox box1 = (TextBox) Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");  
  14.                 TextBox box2 = (TextBox) Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");  
  15.                 DropDownList ddl1 = (DropDownList) Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");  
  16.                 DropDownList ddl2 = (DropDownList) Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");  
  17.                 //get the values from TextBox and DropDownList  
  18.                 //then add it to the collections with a comma "," as the delimited values  
  19.                 sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, ddl2.SelectedItem.Text));  
  20.                 rowIndex++;  
  21.             }  
  22.             //Call the method for executing inserts  
  23.             InsertRecords(sc);  
  24.         }  
  25.     }  
  26. }  

The code above is pretty much straight forward. It simply loops through the data from the DataTable stored in ViewState and then add each row values in a StringCollection. After all the values are added, we then call the method InsertRecords() to actually execute the inserts to the database.

Here's the output below after clicking on the “Save All” button:



And here's the captured data stored in the database:



That's it! I hope you will find this article useful.

I have attached the project for you to download. The project is in Visual Studio 2015. Just look for the file DynamicGrid.aspx and DynamicGrid.aspx.cs to see the code.


Similar Articles