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:

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

Method Definitions

The Events

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. using(SqlConnection connection = new SqlConnection(GetConnectionString()))
  15. {
  16. connection.Open();
  17. using(SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
  18. {
  19. cmd.CommandType = CommandType.Text;
  20. cmd.ExecuteNonQuery();
  21. }
  22. }
  23. lblMessage.Text = "Records successfully saved!";
  24. }

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.