Dynamic Row With Controls On Button Click - Add - Remove

Today, we are going to learn how to create dynamic rows with controls.

Introduction

Dynamic row with controls is useful when you have to add multiple data for multiple items of the same type. On the click of a button, you can add a row with multiple controls and on click of another button, you can delete the particular row. For this, I have used a repeater in ASP.NET.

Creating the project

So, let’s begin. Start your Visual Studio and click on File->New->Website. Select an empty website and give it a name (I have named it “DynamicRow”). Now, let’s drag and drop a repeater to the WebForm. And, let’s add a few controls in it inside the table.

The code will be like below.

  1. <div id="Rpt1">  
  2.     <asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">  
  3.         <ItemTemplate>  
  4.             <table class="table">  
  5.                 <thead>  
  6.                     <tr>  
  7.                         <th>Registration No </th>                                      
  8.                         <th>Category of Vehicle</th>  
  9.                         <th>Insurance Cover Note No</th>  
  10.                         <th>Fitness Certificate</th>                                      
  11.                         <th>Action</th>  
  12.                     </tr>  
  13.                 </thead>  
  14.                 <tbody>  
  15.                     <tr>  
  16.                         <td align="center">  
  17.                             <asp:TextBox autocomplete="off" ID="txtRegNo1" Width="200" runat="server" placeholder="Enter registration no"></asp:TextBox>  
  18.   
  19.                         </td>                                      
  20.   
  21.                         <td align="center">  
  22.                             <asp:DropDownList ID="DdlVehclCatgry1" Width="200" runat="server">  
  23.                                 <asp:ListItem Value="0">Vehicle Category 1</asp:ListItem>  
  24.                                 <asp:ListItem Value="1">Vehicle Category 2</asp:ListItem>  
  25.                                 <asp:ListItem Value="2">Vehicle Category 3</asp:ListItem>  
  26.                                 <asp:ListItem Value="3">Vehicle Category 4</asp:ListItem>  
  27.                             </asp:DropDownList>  
  28.                         </td>  
  29.                         <td align="center">  
  30.                             <asp:TextBox autocomplete="off" ID="txtInsrncCovrNo1" Width="200" runat="server" placeholder="Enter insurance cover note no"></asp:TextBox>  
  31.                         </td>  
  32.   
  33.                         <td align="center">  
  34.                             <asp:FileUpload ID="flupldftnsCert1" runat="server" />  
  35.                         </td>  
  36.                         <td align="center">  
  37.                             <asp:Button ID="BtnDelete" runat="server" Text="Delete Row" />  
  38.   
  39.                         </td>  
  40.                     </tr>  
  41.                 </tbody>  
  42.             </table>  
  43.         </ItemTemplate>  
  44.     </asp:Repeater>  
  45. </div>  

I assume you are familiar with repeater. If you recall, we can add a table inside Repeater under itemtemplate. In the tables, I have arranged 5 controls. The first is a textbox, the second is a DropDownList, the third is again a textbox, the fourth is a fileupload, and the last is a button (for deleting the row).

Let’s also add a button at the top.

  1. <asp:Button ID="BtnAdd" runat="server" Text="Add Vehicle" OnClick="BtnAdd_Click" />  

This button will be used for adding rows.

Now, let’s go to the code behind and add the following code inside the class.

  1. DataTable VehcleDetailsTable = new DataTable();  

This datatable will be used for the repeater.

Now, in the PageLoad method, let’s add the following code.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     VehcleDetailsTable.Columns.Add("DESCRIPTION"); //   
  4.     if (!IsPostBack)  
  5.     {  
  6.         for (int i = 0; i < 0; i++) // LOAD 0 ROWS FOR EXAMPLE  
  7.         {  
  8.             VehcleDetailsTable.Rows.Add(VehcleDetailsTable.NewRow());  
  9.         }  
  10.     }  
  11. }  

We have added a column to the datatable. You can name the column anything you like. I have named it “Description”. In (!IsPostback), we are populating the rows which will be visible when we open the page for the first time. Here, I have used (i < 0) to populate 0 rows. You can increase it to show ‘n’ number of rows by putting (i < n).

  1. VehcleDetailsTable.Rows.Add(VehcleDetailsTable.NewRow());  

The above code adds rows to the repeater.

Now, we will see the “Bind()” method.

  1. protected void Bind()  
  2. {  
  3.     Repeater1.DataSource = VehcleDetailsTable;  
  4.     Repeater1.DataBind();  
  5. }  

Here, we set the datasource of repeater1 as the datatable “VehcleDetailsTable” we created earlier. And bind the repeater.

Now, let’s create another method.

  1. protected void PopulateDataTable()  
  2. {  
  3.     foreach (RepeaterItem item in Repeater1.Items)  
  4.     {  
  5.         TextBox txtDescription = (TextBox)item.FindControl("txtRegNo1");  
  6.         DataRow row = VehcleDetailsTable.NewRow();  
  7.         row["DESCRIPTION"] = txtDescription.Text;  
  8.         VehcleDetailsTable.Rows.Add(row);  
  9.     }  
  10. }  

Here, we are adding rows  to the repeater. You can use the id of any control inside repeater. VehcleDetailsTable.Rows.Add(row); adds the row. We will use this when we are adding the rows in repeater on clicking of our “Add” button.

Now, let’s go to the click event of button control and add the following code.

  1. protected void BtnAdd_Click(object sender, EventArgs e)  
  2. {  
  3.     PopulateDataTable();  
  4.     VehcleDetailsTable.Rows.Add(VehcleDetailsTable.NewRow());  
  5.     Bind();  
  6. }  

Here, we are adding the row with controls in repeater. On single click of button it will add a single row to the repeater.

Now, let’s see how to delete a row. For that, we are using the OnItemCommand="Repeater1_ItemCommand" Event of Repeater. In the code behind, let’s write the following code.

  1. protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)  
  2. {  
  3.     PopulateDataTable();  
  4.     VehcleDetailsTable.Rows[e.Item.ItemIndex].Delete();  
  5.     Bind();  
  6. }  

Here, PopulateDatatableTable populates the repeater and VehcleDetailsTable.Rows[e.Item.ItemIndex].Delete(); deletes the row. After that, we have used Bind() to show the new repeater with deleted row.

This completes our dynamic row creation project. Now, we will see how to access data from the controllers in the repeater.

Let’s add a new button and put the text “Show data from Repeater”. Now, go to the click event of this button and write the following code.

  1. protected void btnShow_Click(object sender, EventArgs e)  
  2. {  
  3.     StringBuilder strbldr = new StringBuilder();  
  4.     foreach (RepeaterItem item in Repeater1.Items)  
  5.     {  
  6.         if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)  
  7.         {  
  8.             TextBox txtRegNo = (TextBox)item.FindControl("txtRegNo1");  
  9.             strbldr.Append(txtRegNo.Text.Trim());  
  10.                   
  11.             DropDownList DdlVehclCatgry = (DropDownList)item.FindControl("DdlVehclCatgry1");  
  12.             strbldr.Append(" " + DdlVehclCatgry.SelectedItem.Text);  
  13.   
  14.             TextBox txtInsrncNoteNo = (TextBox)item.FindControl("txtInsrncCovrNo1");  
  15.             strbldr.Append(" " + txtInsrncNoteNo.Text);  
  16.   
  17.             string FitnessPathRpt = string.Empty;  
  18.             FileUpload FileupldFtnsCertRpt = (FileUpload)item.FindControl("flupldftnsCert1");  
  19.             if (FileupldFtnsCertRpt.HasFile)  
  20.             {  
  21.                       
  22.                 FitnessPathRpt = "FitnessCertificate" + Path.GetExtension(FileupldFtnsCertRpt.FileName).ToLower();  
  23.                 FileupldFtnsCertRpt.PostedFile.SaveAs(Server.MapPath(@"\"+FitnessPathRpt));  
  24.                       
  25.             }  
  26.             strbldr.Append(" " + FitnessPathRpt + "<br />");  
  27.                   
  28.         }  
  29.         Response.Write(strbldr.ToString());  
  30.     }  
  31. }  

Here, we are using the string builder to save data from the controls. The below code is important.

  1. foreach (RepeaterItem item in Repeater1.Items)  
  2. {  
  3.     if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)  

For each item (control) in the repeater, if Itemtype is Item or ItemType is AlternatingItem, to access the controls,

  1. TextBox txtRegNo = (TextBox)item.FindControl("txtRegNo1");  
  2. strbldr.Append(txtRegNo.Text.Trim());  

Access the first control by its ID and append its value to Stringbuilder. Do similarly for other controls in the repeater. At last, show the value of the string builder using Response.Write() method.

This completes our project. You can test it and play with it or even make changes to it. You can also download the code attached with this article. It will work.

Conclusion

 
Dynamic row creation is very useful. I have seen examples with Javascript but sometimes it may not work on Javascript disabled browsers. This one is in pure C#.

It will always work. It is easy, short and understandable.

Thanks folks!


Similar Articles