Add And Delete HTML Table Rows Dynamically Using ASP.NET

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:

CREATE TABLE [dbo].[Employee](  
    [ID] [int] IDENTITY(1,1) NOT NULL,  
    [F_Name] [varchar](50) NULL,  
    [L_Name] [varchar](50) NULL,  
    [Email_ID] [varchar](50) NULL,  
    [Created_Date] [datetime] NOT NULL  
)   
  
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. 

<head runat="server">  
    <title>Demo</title>  
    <meta charset="utf-8" />  
    <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>  
</head>  
<body>  
    <form id="form1" runat="server">  
        <div class="container">  
            <h2>Basic Table</h2>  
            <table class="table" id="maintable">  
                <thead>  
                    <tr>  
                        <th>Firstname</th>  
                        <th>Lastname</th>  
                        <th>Email</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" name="f-name" class="form-control f-name01" /></td>  
                        <td>  
                            <input type="text" name="l-name" class="form-control l-name01" /></td>  
                        <td>  
                            <input type="text" name="email" class="form-control email01" /></td>  
                        <td>  
                            <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
                        </td>  
                    </tr>  
                </tbody>  
            </table>  
            <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-right btn-sm">Submit</button>  
        </div>  
    </form>  
</body>

After adding this, the page will look like the following: 

basic table

Step 3: Adding Controls using jQuery.

<script type="text/javascript">  
    $(document).ready(function () {  
        $(document).on("click", ".classAdd", function () { //
            var rowCount = $('.data-contact-person').length + 1;  
            var contactdiv = '<tr class="data-contact-person">' +  
                '<td><input type="text" name="f-name' + rowCount + '" class="form-control f-name01" /></td>' +  
                '<td><input type="text" name="l-name' + rowCount + '" class="form-control l-name01" /></td>' +  
                '<td><input type="text" name="email' + rowCount + '" class="form-control email01" /></td>' +  
                '<td><button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' +  
                '<button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +  
                '</tr>';  
            $('#maintable').append(contactdiv); // Adding these controls to Main table class  
        });  
    });  
</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.

$(document).on("click", ".deleteContact", function () {  
            $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls   
}); 

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.

public class Employee
{
    public string FName { get;set;}
    public string LName { get; set; }
    public string EmailId { get; set; }
    public DateTime CreatedDate { get; set; }
}

Then we have to write webmethod for making Ajax call on submit button click. This is to store data in the database.

public static string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
[WebMethod]    
public static string SaveData(string empdata)//WebMethod to Save the data  
{    
    var serializeData = JsonConvert.DeserializeObject<List<Employee>>(empdata);    
    using (var con = new SqlConnection(Constr))    
    {    
        foreach (var data in serializeData)    
        {    
            using (var cmd = new SqlCommand("INSERT INTO Employee01 VALUES(@Fname, @Lname,@Email,@CreatedDate)"))    
            {    
                cmd.CommandType = CommandType.Text;    
                cmd.Parameters.AddWithValue("@Fname", data.FName);    
                cmd.Parameters.AddWithValue("@Lname", data.LName);    
                cmd.Parameters.AddWithValue("@Email", data.EmailId);    
                cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);    
                cmd.Connection = con;    
                if (con.State == ConnectionState.Closed)    
                {    
                    con.Open();    
                }    
                cmd.ExecuteNonQuery();    
                con.Close();    
            }    
        }    
    }    
    return null;    
}

Then we have to write Ajax for calling the method.

function getAllEmpData() {    
    var data = [];    
    $('tr.data-contact-person').each(function () {    
        var firstName = $(this).find('.f-name01').val();//Bind to the first name with class f-name01  
        var lastName = $(this).find('.l-name01').val();//Bind to the last name with class l-name01  
        var emailId = $(this).find('.email01').val();//Bind to the emailId with class email01  
        var alldata = {    
            'FName': firstName, //FName as per Employee class name in .cs  
            'LName': lastName, //LName as per Employee class name in .cs  
            'EmailId': emailId //EmailId as per Employee class name in .cs   
        }    
        data.push(alldata);    
    });    
    console.log(data);//  
    return data;    
}    
$("#btnSubmit").click(function () {    
    var data = JSON.stringify(getAllEmpData());    
    //console.log(data);    
    $.ajax({    
        url: 'Home.aspx/SaveData',//Home.aspx is the page   
        type: 'POST',    
        dataType: 'json',    
        contentType: 'application/json; charset=utf-8',    
        data: JSON.stringify({ 'empdata': data }),    
        success: function () {    
            alert("Data Added Successfully");    
        },    
        error: function () {    
            alert("Error while inserting data");    
        }    
    });    
});

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:

var serializeData = JsonConvert.DeserializeObject<List<Employee>>(empdata);  

Define connection string in web.config as follows:

<connectionStrings>  
   <add name="constr" connectionString="Data Source=(local);Initial Catalog=UsersDB;User id = ; password=*********" providerName="System.Data.SqlClient" />  
</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.


Similar Articles