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
- HTML tables are light weight as compared to GridView of ASP.NET Server Control.
- 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:

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:

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.

Shailesh PandeyPosted May 10, 2020, 6:46 AM
Jquery.js:9664 POST http://localhost:44360/Home.aspx/SaveData net::ERR_CONNECTION_RESETsend @ jquery.js:6931 ajax @ jquery.js:6931 (anonymous) @ Home:91 dispatch @ jquery.js:3707 r.handle @ jquery.js:3707
Shailesh PandeyPosted May 10, 2020, 6:45 AM
Failed to load resource: net::ERR_CONNECTION_RESET
Shailesh PandeyPosted May 10, 2020, 6:44 AM
Error while inserting data
Shailesh PandeyPosted May 10, 2020, 6:44 AM
Copied your same code but when I save the details unable to store data in database
Maria PrincePosted Mar 13, 2020, 6:40 AM
Thanks for Sharing
Aliya khanPosted Aug 31, 2019, 5:21 AM
Thanks for this ,i use this but i can't able to remove the 2nd row which is added dynamically?
Aliya khanPosted Aug 29, 2019, 3:33 AM
How to add new row if we have to get the data from multilple tables?
Hussnain SajidPosted Jul 1, 2019, 2:58 AM
Hope you are Good ! I copied your code everything works fine for me but when I save the details the empty row also inserts in the db tell me what to do? Thanks in advance
arsal younaPosted Aug 21, 2018, 9:11 AM
I copied the same code. Everything is working fine except Ajax call is not being made in visual studio 2015 and I am unable to store data in database, Kindly suggest solutions.
arsal younaPosted Aug 16, 2018, 6:14 AM
I want to dynamically add data from database and populate these fields dynamically. Kindly suggest how can I assign values to these fields from database
Tabarak HussainPosted Jul 29, 2018, 2:30 AM
Excellent, Thanks for sharing.
Vinod VishwakarmaPosted May 25, 2018, 6:08 AM
Can i add extra variable in insert query which is not part of GetAllEmpData Function of html???
Emran EmonPosted Apr 23, 2018, 1:56 PM
Nice Sir, Thanks for Sharing
Phuong NguyenPosted Oct 11, 2017, 11:38 AM
Tks share i have problem and see it
Pratik ShirsePosted Feb 6, 2017, 5:40 AM
Good one sir how to do calculation of particular row
SubashPosted Aug 1, 2016, 5:38 AM
Nice
kalu singh raoPosted Jul 22, 2016, 2:44 AM
Nice share
Vikash PatelPosted Mar 30, 2016, 6:19 AM
mast hai but i want to add calendar with all textbox
Michael JohnstonPosted Jan 5, 2016, 1:10 PM
Excellent code. Thank you for sharing it. Is there a way to add validation, such as required to the inputs?
Ekrem TapanPosted Nov 3, 2015, 8:31 PM
Good article
Humayun Kabir MamunPosted Sep 11, 2015, 2:34 AM
Nice...
Pratham DavePosted Sep 10, 2015, 1:25 PM
superb job.. keep it up..!
ROHAN THAKURPosted Sep 10, 2015, 2:47 AM
good one sir... Thanks for sharing....
Shridhar SharmaPosted Sep 7, 2015, 4:59 PM
nice share
Santhakumar MunuswamyPosted Sep 7, 2015, 2:33 PM
Thanks for nice share
RakeshPosted Sep 7, 2015, 12:54 PM
Good Explain sir
Mohammed IbrahimPosted Sep 7, 2015, 11:52 AM
Nice explaination
Debasis SahaPosted Sep 7, 2015, 9:41 AM
Good one..
Pankaj Kumar ChoudharyPosted Sep 7, 2015, 9:02 AM
Nice Explain Sir........
Upendra Pratap ShahiPosted Sep 7, 2015, 7:50 AM
good start.... keep it up
Ratnesh SinghPosted Sep 7, 2015, 7:03 AM
nice..
Karthikeyan KPosted Sep 7, 2015, 7:02 AM
Good one sir...Thanks for sharing