In this article I will explain with an example, how to perform Add, Edit, Update and Delete in GridView with Paging using AJAX in ASP.Net using C# and VB.Net.
 
 
Database
I have made use of the following table Customers with the schema as follows.
GridView - Add Edit Update Delete and Paging the AJAX way
 
I have already inserted few records in the table.
GridView - Add Edit Update Delete and Paging the AJAX way
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
HTML Markup
The HTML Markup consists of:
ScriptManager – For enabling AJAX.
UpdatePanel – For enabling partial page refresh.
GridView:–
Columns
GridView consists of two TemplateField columns and a CommandField column.
TemplateField – Name and Country fields are set in the TemplateField columns with ItemTemplate with a Label and EditItemTemplate with TextBox for displaying and editing data respectively.
 
Properties
DataKeyNames – For storing the Unique key values such as Primary Key, ID fields, etc.
Note: For more details on DataKeys, please refer my article DataKeyNames in GridView example in ASP.Net.
 
PageSize – For permitting maximum number of rows to be displayed per page.
AllowPaging – For enabling paging in the GridView control.
EmptyDataText – For displaying text when there is no data in the GridView.
 
Events
GridView has been assigned with the following five event handlers i.e. OnRowDataBound, OnRowEditing, OnRowCancelingEdit, OnRowUpdating, OnPageIndexChanging and OnRowDeleting.
 
TextBox – For capturing records to be added.
Button – For adding records.
The Button has been assigned with an OnClick event handler.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div id="dvGrid" style="padding: 10px; width: 450px">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"
                DataKeyNames="CustomerId" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
                PageSize="3" AllowPaging="true" OnPageIndexChanging="OnPaging"
OnRowUpdating="OnRowUpdating"
                OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." Width="450">
                <Columns>
                    <asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>' Width="140"></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
                        <ItemTemplate>
                            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>' Width="140"></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
                        ItemStyle-Width="150" />
                </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: 150px">
                        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Binding the GridView with records from SQL Database Table
Inside the Page Load event handler, the BindGrid method is called and the GridView is populated with records from the Customers table of SQL Server database.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM Customers";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
        {
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                gvCustomers.DataSource = dt;
                gvCustomers.DataBind();
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM Customers"
    Using con As SqlConnection = New SqlConnection(constr)
        Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
            Using dt As DataTable = New DataTable()
                sda.Fill(dt)
                gvCustomers.DataSource = dt
                gvCustomers.DataBind()
            End Using
        End Using
    End Using
End Sub
 
 
Insert
When the Add Button is clicked, the name and the country values are fetched from their respective TextBoxes and are inserted into the SQL Server database.
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void Insert(object sender, EventArgs e)
{
    string name = txtName.Text;
    string country = txtCountry.Text;
    txtName.Text = "";
    txtCountry.Text = "";
    string query = "INSERT INTO Customers VALUES(@Name, @Country)";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@Country", country);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
 
    this.BindGrid();
}
 
VB.Net
Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim name As String = txtName.Text
    Dim country As String = txtCountry.Text
    Dim query As String = "INSERT INTO Customers VALUES(@Name, @Country)"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    txtName.Text = ""
    txtCountry.Text = ""
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Parameters.AddWithValue("@Name", name)
            cmd.Parameters.AddWithValue("@Country", country)
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
 
    Me.BindGrid()
End Sub
 
 
Edit
When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered, where the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
    gvCustomers.EditIndex = e.NewEditIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    gvCustomers.EditIndex = e.NewEditIndex
    Me.BindGrid()
End Sub
 
 
Update
When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.
Inside the OnRowUpdating event handler, the CustomerId (primary key) is fetched from the DataKey property of GridView while the Name and Country fields are fetched from their respective TextBoxes and the record is updated in the database.
Note: For more details on DataKeys please refer my article DataKeyNames in GridView example in ASP.Net.
 
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = gvCustomers.Rows[e.RowIndex];
    int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
    string name = (row.FindControl("txtName") as TextBox).Text;
    string country = (row.FindControl("txtCountry") as TextBox).Text;
    string query = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
           cmd.Parameters.AddWithValue("@CustomerId", customerId);
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@Country", country);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    gvCustomers.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    Dim row As GridViewRow = gvCustomers.Rows(e.RowIndex)
    Dim customerId As Integer = Convert.ToInt32(gvCustomers.DataKeys(e.RowIndex).Values(0))
    Dim name As String = (TryCast(row.FindControl("txtName"), TextBox)).Text
    Dim country As String = (TryCast(row.FindControl("txtCountry"), TextBox)).Text
    Dim query As String = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            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
    gvCustomers.EditIndex = -1
    Me.BindGrid()
End Sub
 
 
Cancel Edit
When the Cancel Button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered and the EditIndex is set to -1 and the GridView is populated with data using the BindGrid method.
C#
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
    gvCustomers.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowCancelingEdit(ByVal sender As Object, ByVal e As EventArgs)
    gvCustomers.EditIndex = -1
    Me.BindGrid()
End Sub
 
 
Delete
When the Delete Button is clicked, the GridView’s OnRowDeleting event handler is triggered.
Inside the OnRowDeleting event handler, the CustomerId (primary key) is fetched from the DataKey property of GridView and the record is deleted in the database.
Note: For more details on DataKeys please refer my article DataKeyNames in GridView example in ASP.Net.
 
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
    string query = "DELETE FROM Customers WHERE CustomerId=@CustomerId";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Parameters.AddWithValue("@CustomerId", customerId);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
 
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
    Dim customerId As Integer = Convert.ToInt32(gvCustomers.DataKeys(e.RowIndex).Values(0))
    Dim query As String = "DELETE FROM Customers WHERE CustomerId=@CustomerId"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Parameters.AddWithValue("@CustomerId", customerId)
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
 
    Me.BindGrid()
End Sub
 
 
Delete Confirmation Message
The delete operation will be confirmed using JavaScript Confirmation Box, thus inside the OnRowDataBound event handler, the Delete LinkButton is assigned with a JavaScript onclick event handler.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != gvCustomers.EditIndex)
    {
        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
    }
}
 
VB.Net
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow And Also e.Row.RowIndex <> gvCustomers.EditIndex Then
        CType(e.Row.Cells(2).Controls(2), LinkButton).Attributes("onclick") = "return confirm('Do you want to delete this row?');"
    End If
End Sub
 
 
Paging
Inside the OnPageIndexChanging event handler, the PageIndex property of the GridView is updated with the new Page Number which was clicked.
Finally, the GridView is populated using the BindGrid method which in-turn displays the new GridView page.
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    gvCustomers.PageIndex = e.NewPageIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    gvCustomers.PageIndex = e.NewPageIndex
    Me.BindGrid()
End Sub
 
 
Displaying AJAX Loading progress during Add, Edit, Update, Delete and Paging operations
jQuery BlockUI plugin Implementation
Inside the HTML, the following jQuery blockUI and jQuery JS files are inherited.
1. jquery-ui.js
2. jquery.blockUI.js
Note: In order to make use of BlockUI plugin, you need to make use of jQuery version 1.8.3.
 
Inside the jQuery document ready event handler, an HTML DIV is displayed when the ASP.Net AJAX UpdatePanel makes an AJAX request.
The HTML DIV is applied with the jQuery BlockUI Plugin which blocks the area and displays an animation.
When the AJAX request is completed, the HTML DIV is unblocked and the animation is hidden.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.blockUI.js"></script>
<script type="text/javascript">
    $(function () {
        BlockUI("dvGrid");
        $.blockUI.defaults.css = {};
    });
    function BlockUI(elementID) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(function () {
            $("#" + elementID).block({ message: '<div align = "center">' + '<img src="images/loadingAnim.gif"/></div>',
                css: {},
                overlayCSS: { backgroundColor: '#000000', opacity: 0.6, border: '3px solid #63B2EB' }
            });
        });
        prm.add_endRequest(function () {
            $("#" + elementID).unblock();
        });
    };
</script>
 
 
Screenshot
GridView - Add Edit Update Delete and Paging the AJAX way
 
 
Downloads