In this article I will explain with an example, how to perform select, insert, edit, update and delete operations in GridView without using PostBack in ASP.Net using C# and VB.Net.
This process is also known as CRUD i.e. Create, Read, Update and Delete in GridView.
The CRUD operation will be done without using PostBack using jQuery AJAX in ASP.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of an ASP.Net GridView with some LinkButtions for various operations i.e. Edit, Update, Cancel and Delete.
The first column consists of a Label control while the other two columns consists of a Label and a hidden TextBox. The TextBox will be made visible while performing Edit and Update operations in the GridView.
Below the GridView there’s a Form for inserting data into Customers table using jQuery AJAX.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Customer Id" ItemStyle-Width="110px" ItemStyle-CssClass="CustomerId">
<ItemTemplate>
<asp:Label Text='<%# Eval("CustomerId") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
<asp:TextBox Text='<%# Eval("Name") %>' runat="server" Style="display: none" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
<ItemTemplate>
<asp:Label Text='<%# Eval("Country") %>' runat="server" />
<asp:TextBox Text='<%# Eval("Country") %>' runat="server" Style="display: none" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CssClass="Edit" />
<asp:LinkButton Text="Update" runat="server" CssClass="Update" Style="display: none" />
<asp:LinkButton Text="Cancel" runat="server" CssClass="Cancel" Style="display: none" />
<asp:LinkButton Text="Delete" runat="server" CssClass="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 150px">
Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" />
</td>
<td style="width: 100px">
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" />
</td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Populating GridView with Dummy Data
In Page Load event of the page, the GridView is populated with dummy data in order to use its HTML Table structure to populate data using jQuery AJAX.
Note: The dummy DataTable being populated has the same columns which will be returned from the SQL Query.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindDummyRow();
}
}
private void BindDummyRow()
{
DataTable dummy = new DataTable();
dummy.Columns.Add("CustomerId");
dummy.Columns.Add("Name");
dummy.Columns.Add("Country");
dummy.Rows.Add();
gvCustomers.DataSource = dummy;
gvCustomers.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindDummyRow()
End If
End Sub
Private Sub BindDummyRow()
Dim dummy As New DataTable()
dummy.Columns.Add("CustomerId")
dummy.Columns.Add("Name")
dummy.Columns.Add("Country")
dummy.Rows.Add()
gvCustomers.DataSource = dummy
gvCustomers.DataBind()
End Sub
WebMethods for handling CRUD operations
Following are the WebMethods used for handling CRUD operations i.e. select, insert, edit, update and delete operations in GridView.
GetCustomers
The GetCustomers WebMethod simply fetches all records present in the Customers table and returns it as an XML string.
InsertCustomer
The InsertCustomer WebMethod accepts Name and Country values as parameters and after inserting the record into the Customers Table, it returns the CustomerId of the inserted record.
UpdateCustomer
The UpdateCustomer WebMethod accepts CustomerId, Name and Country values as parameters and using the CustomerId, the Name and Country values are updated in the Customers Table.
DeleteCustomer
The DeleteCustomer WebMethod accepts CustomerId as parameter and using the CustomerId, the record is deleted from the Customers Table.
C#
[WebMethod]
public static string GetCustomers()
{
string query = "SELECT CustomerId, Name, Country FROM Customers";
SqlCommand cmd = new SqlCommand(query);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
}
[WebMethod]
public static int InsertCustomer(string name, string country)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name, @Country) SELECT SCOPE_IDENTITY()"))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Connection = con;
con.Open();
int customerId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return customerId;
}
}
}
[WebMethod]
public static void UpdateCustomer(int customerId, string name, string country)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
[WebMethod]
public static void DeleteCustomer(int customerId)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
<WebMethod()> _
Public Shared Function GetCustomers() As String
Dim query As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim cmd As New SqlCommand(query)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds)
Return ds.GetXml()
End Using
End Using
End Using
End Function
<WebMethod()> _
Public Shared Function InsertCustomer(name As String, country As String) As Integer
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO Customers VALUES(@Name, @Country) SELECT SCOPE_IDENTITY()")
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
cmd.Connection = con
con.Open()
Dim customerId As Integer = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
Return customerId
End Using
End Using
End Function
<WebMethod()> _
Public Shared Sub UpdateCustomer(customerId As Integer, name As String, country As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId")
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
<WebMethod()> _
Public Shared Sub DeleteCustomer(customerId As Integer)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId")
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Populating GridView using jQuery AJAX
Inside the jQuery document ready event handler, an AJAX call is made to the GetCustomers WebMethod and the XML string is received as response.
The XML string is parsed using jQuery and a loop is executed over the records present in the XML string.
Inside the loop, the dummy GridView row is cloned, the values are set and the row is appended to the GridView using the AppendRow function.
Finally the dummy row is removed from the GridView.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var row = $("[id*=gvCustomers] tr:last-child").clone(true);
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
AppendRow(row, $(this).find("CustomerId").text(), $(this).find("Name").text(), $(this).find("Country").text())
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
}
function AppendRow(row, customerId, name, country) {
//Bind CustomerId.
$(".CustomerId", row).find("span").html(customerId);
//Bind Name.
$(".Name", row).find("span").html(name);
$(".Name", row).find("input").val(name);
//Bind Country.
$(".Country", row).find("span").html(country);
$(".Country", row).find("input").val(country);
$("[id*=gvCustomers]").append(row);
}
</script>
Inserting records to GridView
The following event handler is executed when the Add Button is clicked. The name and the country values are fetched from their respective TextBoxes and then passed to the InsertCustomer WebMethod using jQuery AJAX call.
Once the response is received, a new row is appended to the GridView using the AppendRow function.
<script type="text/javascript">
//Add event handler.
$("body").on("click", "[id*=btnAdd]", function () {
var txtName = $("[id*=txtName]");
var txtCountry = $("[id*=txtCountry]");
$.ajax({
type: "POST",
url: "Default.aspx/InsertCustomer",
data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var row = $("[id*=gvCustomers] tr:last-child").clone(true);
AppendRow(row, response.d, txtName.val(), txtCountry.val());
txtName.val("");
txtCountry.val("");
}
});
return false;
});
</script>
Editing and Updating GridView records
Edit
When the Edit Button is clicked, the reference of the GridView row is determined and the Label controls is made hidden while the TextBox controls are made visible in the Name and Country columns of the GridView control.
<script type="text/javascript">
//Edit event handler.
$("body").on("click", "[id*=gvCustomers] .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
row.find(".Delete").hide();
$(this).hide();
return false;
});
</script>
Update
When the Update Button is clicked, the reference of the GridView row is determined and the updated values are fetched from the respective TextBoxes of Name and Country columns while the CustomerId is determined from the CustomerId column.
The values of CustomerId, Name and Country are passed to the UpdateCustomer WebMethod using jQuery AJAX call.
Once the response is received, the Label controls are made visible and the TextBox controls are made hidden for the Name and Country columns of the GridView control.
<script type="text/javascript">
//Update event handler.
$("body").on("click", "[id*=gvCustomers] .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Delete").show();
row.find(".Cancel").hide();
$(this).hide();
var customerId = row.find(".CustomerId").find("span").html();
var name = row.find(".Name").find("span").html();
var country = row.find(".Country").find("span").html();
$.ajax({
type: "POST",
url: "Default.aspx/UpdateCustomer",
data: '{customerId: ' + customerId + ', name: "' + name + '", country: "' + country + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
</script>
Cancel
When the Cancel Button is clicked, the reference of the GridView row is determined and the Label controls are made visible while the TextBox controls are made hidden in the Name and Country columns of the GridView control.
<script type="text/javascript">
//Cancel event handler.
$("body").on("click", "[id*=gvCustomers] .Cancel", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
var span = $(this).find("span");
var input = $(this).find("input");
input.val(span.html());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Delete").show();
row.find(".Update").hide();
$(this).hide();
return false;
});
</script>
Deleting GridView records
When the Delete Button is clicked, the reference of the GridView row is determined and the value of the CustomerId is fetched and passed to the DeleteCustomer WebMethod using jQuery AJAX call.
Once the response is received the respective row is removed from the GridView.
<script type="text/javascript">
//Delete event handler.
$("body").on("click", "[id*=gvCustomers] .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var customerId = row.find("span").html();
$.ajax({
type: "POST",
url: "Default.aspx/DeleteCustomer",
data: '{customerId: ' + customerId + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
row.remove();
}
});
}
return false;
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads