Add And Delete HTML Table Rows Dynamically Using ASP.NET

This article demonstrates how to add and delete HTML table rows dynamically at run time and save all the rows into the database.

Introduction

This article demonstrates how to add and delete HTML table rows dynamically at run time and save all the rows into the database using ASP.NET C#, jQuery and Ajax.

Benefits of Using HTML Table
  1. HTML tables are light weight as compared to GridView of ASP.NET Server Control.
  2. We will be adding and deleting rows using jQuery from the client side.

Let's see how to create the application:

Step 1: 
Creating SQL Table.

SQL Table structure for this application like the following:

 

The SQL query as per the above structure is shown here:
  1. CREATE TABLE [dbo].[Employee](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [F_Name] [varchar](50) NULL,  
  4.     [L_Name] [varchar](50) NULL,  
  5.     [Email_ID] [varchar](50) NULL,  
  6.     [Created_Date] [datetime] NOT NULL  
  7. )   
  8.   
  9. ALTER TABLE [dbo].[Employee] ADD  CONSTRAINT [DF_Employee01_Created_Date]  DEFAULT (getdate()) FOR [Created_Date] 
Step 2: Designing ASPX Page.

Here I have used bootstrap for better look and feel, but you can use your own css.
  1. <head runat="server">  
  2.     <title>Demo</title>  
  3.     <meta charset="utf-8" />  
  4.     <meta name="viewport" content="width=device-width, initial-scale=1" />  
  5.     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  7.     <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.         <div class="container">  
  12.             <h2>Basic Table</h2>  
  13.             <table class="table" id="maintable">  
  14.                 <thead>  
  15.                     <tr>  
  16.                         <th>Firstname</th>  
  17.                         <th>Lastname</th>  
  18.                         <th>Email</th>  
  19.                     </tr>  
  20.                 </thead>  
  21.                 <tbody>  
  22.                     <tr class="data-contact-person">  
  23.                         <td>  
  24.                             <input type="text" name="f-name" class="form-control f-name01" /></td>  
  25.                         <td>  
  26.                             <input type="text" name="l-name" class="form-control l-name01" /></td>  
  27.                         <td>  
  28.                             <input type="text" name="email" class="form-control email01" /></td>  
  29.                         <td>  
  30.                             <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
  31.                         </td>  
  32.                     </tr>  
  33.                 </tbody>  
  34.             </table>  
  35.             <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-right btn-sm">Submit</button>  
  36.         </div>  
  37.     </form>  
  38. </body> 
After adding this, the page will look like the following: 

basic table

Step 3:
Adding Controls using jQuery.
  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         $(document).on("click"".classAdd"function () { //
  4.             var rowCount = $('.data-contact-person').length + 1;  
  5.             var contactdiv = '<tr class="data-contact-person">' +  
  6.                 '<td><input type="text" name="f-name' + rowCount + '" class="form-control f-name01" /></td>' +  
  7.                 '<td><input type="text" name="l-name' + rowCount + '" class="form-control l-name01" /></td>' +  
  8.                 '<td><input type="text" name="email' + rowCount + '" class="form-control email01" /></td>' +  
  9.                 '<td><button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' +  
  10.                 '<button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +  
  11.                 '</tr>';  
  12.             $('#maintable').append(contactdiv); // Adding these controls to Main table class  
  13.         });  
  14.     });  
  15. </script> 
I have added controls on the basis of Add More button click with class name classAdd.

Here I am adding new <tr> with class name data-contact-person.

At last I am appending this to my table with my table Id as maintable.

Also, I am creating a new button for removing that particular row as my 1st row will be fixed and we can't remove it.

Note: You can't write add controls on the basis of Id of the button as the Id will be different on each addition.
 
Step 4: Removing a particular row.
  1. $(document).on("click"".deleteContact"function () {  
  2.             $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls   
  3. }); 
Since everytime I am adding new rows with <tr>, I have to remove this using closet() on remove button click with class name deleteContact.
After this step the design will look like the following:

design
 
Step 5: Saving all the rows into the database.

Firstly, we have to create an Employee Class in the .cs page.
  1. public class Employee
  2. {
  3.     public string FName { get;set;}
  4.     public string LName { getset; }
  5.     public string EmailId { getset; }
  6.     public DateTime CreatedDate { getset; }
  7. }
Then we have to write webmethod for making Ajax call on submit button click. This is to store data in the database.
  1. public static string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  2. [WebMethod]    
  3. public static string SaveData(string empdata)//WebMethod to Save the data  
  4. {    
  5.     var serializeData = JsonConvert.DeserializeObject<List<Employee>>(empdata);    
  6.     using (var con = new SqlConnection(Constr))    
  7.     {    
  8.         foreach (var data in serializeData)    
  9.         {    
  10.             using (var cmd = new SqlCommand("INSERT INTO Employee01 VALUES(@Fname, @Lname,@Email,@CreatedDate)"))    
  11.             {    
  12.                 cmd.CommandType = CommandType.Text;    
  13.                 cmd.Parameters.AddWithValue("@Fname", data.FName);    
  14.                 cmd.Parameters.AddWithValue("@Lname", data.LName);    
  15.                 cmd.Parameters.AddWithValue("@Email", data.EmailId);    
  16.                 cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);    
  17.                 cmd.Connection = con;    
  18.                 if (con.State == ConnectionState.Closed)    
  19.                 {    
  20.                     con.Open();    
  21.                 }    
  22.                 cmd.ExecuteNonQuery();    
  23.                 con.Close();    
  24.             }    
  25.         }    
  26.     }    
  27.     return null;    
  28. }  
Then we have to write Ajax for calling the method.
  1. function getAllEmpData() {    
  2.     var data = [];    
  3.     $('tr.data-contact-person').each(function () {    
  4.         var firstName = $(this).find('.f-name01').val();//Bind to the first name with class f-name01  
  5.         var lastName = $(this).find('.l-name01').val();//Bind to the last name with class l-name01  
  6.         var emailId = $(this).find('.email01').val();//Bind to the emailId with class email01  
  7.         var alldata = {    
  8.             'FName': firstName, //FName as per Employee class name in .cs  
  9.             'LName': lastName, //LName as per Employee class name in .cs  
  10.             'EmailId': emailId //EmailId as per Employee class name in .cs   
  11.         }    
  12.         data.push(alldata);    
  13.     });    
  14.     console.log(data);//  
  15.     return data;    
  16. }    
  17. $("#btnSubmit").click(function () {    
  18.     var data = JSON.stringify(getAllEmpData());    
  19.     //console.log(data);    
  20.     $.ajax({    
  21.         url: 'Home.aspx/SaveData',//Home.aspx is the page   
  22.         type: 'POST',    
  23.         dataType: 'json',    
  24.         contentType: 'application/json; charset=utf-8',    
  25.         data: JSON.stringify({ 'empdata': data }),    
  26.         success: function () {    
  27.             alert("Data Added Successfully");    
  28.         },    
  29.         error: function () {    
  30.             alert("Error while inserting data");    
  31.         }    
  32.     });    
  33. });  
See btnSubmit is the Id of my button and Home.aspx is the page and SaveData is the Web method.

See getAllEmpData() function and its binding and read the comments for better understanding.

Also here I have added Newtonsoft.Json.dll from Nuget Packet manager as I will be getting data in JSON format and  deserialized them in the Web Method of .cs page like the following snippet:
  1. var serializeData = JsonConvert.DeserializeObject<List<Employee>>(empdata);  
Define connection string in web.config as follows:
  1. <connectionStrings>  
  2.    <add name="constr" connectionString="Data Source=(local);Initial Catalog=UsersDB;User id = ; password=*********" providerName="System.Data.SqlClient" />  
  3.  </connectionStrings> 
After doing this you can see all the data has been added in your database and you can retrieve and display as per your requirements.

Note:
  • You should have minimum knowledge of jQuery and Ajax before using this.
  • Make sure JavaScript is enabled in your browser.