Home > ASP.Net, Jquery > Use JQuery to Delete from Gridview

Use JQuery to Delete from Gridview


Hi

try this example to JQuery to Delete from Gridview

Step1 :- Go to JQuery site and Download jquery-1.4.min.js from here

Step2 :- Create a new website and add new web page and Web.Config file

Step3 :- in Web page add Gridview and use SQLDataSource control to bind in it

Note : in this example i’m using Northwind Database

So the web page will be :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView and JQuery</title>
    <script src="Script/jquery-1.4.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {
             $("#.delbutton").click(function() {
                 //Get the Id of the record to delete
                 var record_id = $(this).attr("id");
                 //Get the GridView Row reference
                 var tr_id = $(this).parents("#.record");
                 // Ask user's confirmation before delete records
                 if (confirm("Do you want to delete this record?")) {
                     $.ajax({
                         type: "POST",
                         //GridViewDelete.aspx is the page name and DeleteUser is the server side method to delete records in GridViewDelete.aspx.cs
                         url: "Default.aspx/DeleteCategory",
                         //Pass the selected record id
                         data: "{'args': '" + record_id + "'}",
                         contentType: "application/json; charset=utf-8",
                         dataType: "json",
                         success: function() {
                             // Change the back color of the Row before deleting
                             tr_id.css("background-color", "lightgreen");
                             // Do some animation effect
                             tr_id.fadeOut(500, function() {
                                 //Remove GridView row
                                 tr_id.remove();
                             });
                         }
                     });
                 }
                 return false;
             });
         });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"
            ForeColor="#333333">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
                    InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
                    SortExpression="CategoryName" />
                <asp:TemplateField>
                    <ItemTemplate>
                     <a href="#" id='<%# Eval("CategoryID") %>'> <img  border="0" src="Images/delete.jpg" alt="Delete" /></a>
                  </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]">
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

Step4 :- in code behind add the following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static void DeleteCategory(string args)
    {
        string conString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection sqlConn = new SqlConnection(conString);
        try
        {
            SqlCommand sqlCmd = new SqlCommand("Delete from Categories where CategoryID = @CategoryID", sqlConn);
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.Parameters.AddWithValue("@CategoryID", Convert.ToInt32(args.Trim()));
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
        }
        catch
        {
            //Handle Error
        }
        finally
        {
            sqlConn.Close();
        }
    }
}

Step5 :- in Web.Config file add the connection String

<connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net, Jquery
  1. Nitesh
    October 3, 2011 at 8:21 am

    very helpful. Thank you. Just what I needed. Saved me tons of time on research and development

  2. yasserzaid
    October 3, 2011 at 7:39 pm

    @Nitesh :- you are welcome hope my post helps you

  1. July 2, 2014 at 12:28 am
  2. July 3, 2014 at 9:14 pm
  3. July 5, 2014 at 12:19 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: