.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Delete row from GridView and Database using JQuery in asp.net

Posted By:Pankaj Mishra       Posted Date: February 17, 2010    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  

In this article we are Going to see how can we Delete records row from GridView and Database SQL Server using JQuery when user click on delete button in a GridView
 

Delete row or records from GridView and Database using JQuery in asp.net.

Introduction

As we know JQuery can be seen as an alternate of ajax hence we can do some operation in GridView using JQuery like deleting the records or row from GridView is much easier.

As we all know that GridView is render in the client browser as HTML mark up tag like table

, as GridView row and that means entire row from gridview.

We are going to use css to recognize the

as GridView row and using JQuery we are going to remove the tag which means use will get a feel that on click of delete image or button

In this article we are not going to use Update panel but using JQuery it will give similar feel mean without page postback delete the records.

Other Articles on JQuery:

GridView and JQuery

you can find the other articles on JQuery to call server side function here

To Check the username availability live using JQuery you can visit this article

To Perform various validation in asp.net application using JQuery you can visit this post.

1st create user table with below columns in sql server database

Craete SQL Server Table

CREATE TABLE [dbo].[User_Table](
 [Id] [int] NOT NULL,
 [User_Name] [varchar](30) NOT NULL,
 [First_Name] [varchar](50) NOT NULL,
 [Last_Name] [varchar](50) NOT NULL,
 [Middle_Name] [varchar](50) NOT NULL,
 [Email_Id] [varchar](70) NOT NULL
) ON [PRIMARY]

You can add some records manually in the newly created table

Now lets create 2 stored procedure one to fetch records from database and display to GridView and other one is for deleting the records from database table.

This sp is for Fetching Records from User_Table

Craete Stored Proceure

CREATE PROCEDURE [dbo].[GetUserRecords]
AS 
BEGIN 

 SELECT * FROM dbo.User_Table

END

and this stored procedure one is for Deleting records

CREATE PROCEDURE [dbo].[DeleteUser](@id int)
AS 
BEGIN 

 DELETE FROM dbo.User_Table WHERE id = @id

END

Now Drag and Drop the GridView from the toolbox of the visual studio and place into the web form and depending upon the your requirement you can set the autogenerated column to false and Bound column or template column, Its totally up to you and your requirement.

In the below example I have taken 6 bound column and one template column for delete hyperlink and image button

GridView in .aspx page


        
          
              
              
              
              
               
              
              
                  
                      Delete
                  
              
          
    


In the above GridView code I have used to set the class to record and its important to delete row using JQuery

In the above declaration of GridView I also used anchor tag and set its class to delbutton and its id value to the  correspondent to the database id column so that we can get the record id in JQuery function.

Now assign the data to the gridView in the page load event

 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadData();
        }
    }


 
 and here is the LoadData function which will get the data from SQL Server using Stored Procedure and bind to GridView
 
 

private void LoadData()
    {
        //Get the connection string from the web.config file
        string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

        SqlConnection sqlConn = new SqlConnection(conString);

        try
        {

            SqlCommand sqlCmd = new SqlCommand("GetUserRecords", sqlConn);

            sqlCmd.CommandType = CommandType.StoredProcedure;

            sqlConn.Open();

            SqlDataReader rdr = sqlCmd.ExecuteReader();

            //assign datareader to GridView you can assign to any datasource for e.g DataTable or dataSet
            GridView1.DataSource = rdr;
            GridView1.DataBind();

            //Close DataReader
            rdr.Close();
        }
        catch
        {
            //Handle Error if any occurred
        }
        finally
        {
            //Close Database connection
            sqlConn.Close();
        }
    }


Once you bind the data into grridview you will see this

And Below is the code which is used to delete records from database and will be called using Jquery. Don't forget to add  [System.Web.Services.WebMethod] like this

 

    [System.Web.Services.WebMethod]
    public static void DeleteUser(string args)
    {

        string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

        SqlConnection sqlConn = new SqlConnection(conString);

        try
        {

            SqlCommand sqlCmd = new SqlCommand("DeleteUser", sqlConn);

            sqlCmd.CommandType = CommandType.StoredProcedure;

            sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(args.Trim()));

            sqlConn.Open();

            sqlCmd.ExecuteNonQuery();

        }
        catch
        {
            //Handle Exception
        }
        finally
        {
            sqlConn.Close();
        }

    }


 
Now Here is the JQuery code sample

JQuery Delete function


    GridView and JQuery

    
     

If you wun the application and click on any delete image it will ask the confirmation like below image and if you say yes it will delete the omage from the UI and Database

Hope this will help all. You can also donwload the sample application by licking the below download link

Cheers
Pankaj!!!

as GridView cell. Actually in this article we will remove the
Download
pankaj_634020323215182304_JQuerySample.zip

 Subscribe to Articles

     

Further Readings:

Responses
Author: Hasmukh         Company URL: http://www.dotnetspark.com
Posted Date: June 22, 2010

hi,
the sample given by you is not running at my end
i just followed all your step and downloaded your sample but its not working

I think you have not provided the css files because it highlight two things

class="delbutton"

&

CssClass="record"

please correct me if i am wrong and provide me the perfect solution it will be greate help for me
Thank you all
Hasmukh Jain

Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: June 22, 2010

Hi,

css file is not required as this is for reference to get the row id from JQuery. The sample project is working.

Sample application require database entry might be that is the problem

Thanks
Pankaj
Author: von sazkin         Company URL: http://www.dotnetspark.com
Posted Date: July 30, 2010

Hi Pankaj,

Thanks for this excellent post. What if I want to replace the confirm dialog with the JQuery UI Dialog box? How will I achieve that?

So when the user clicks on the delete button or image, it pops the JQuery dialog box asking for confirmation. If user says Yes, it deletes the record, else it does not and closes.

Thanks!
Author: ajeet         Company URL: http://www.dotnetspark.com
Posted Date: November 01, 2010

pankaj,

I am using mozilla firebox(3.5) but this code is not working on mozila when i run this code on internet Explorer this is running fine.
I am geting following error on Mozilla firebox:
Syntax error, unrecognized expression: #
Please Help me
Author: Ankush         Company URL: http://www.dotnetspark.com
Posted Date: November 30, 2010

Hi Pankaj,

Thanks for this excellent post it helps me a lot.
I am getting the same problem as ajeet getting.
I am using Mozilla firefox(3.6) and this code is not working while in IE 8 it is working fine.

Please Help me..


Thanks & Regards
Ankush Mahajan
Author: Ankush         Company URL: http://www.dotnetspark.com
Posted Date: November 30, 2010

The problem has been solved.
write the function like this
$(".delbutton").click(function ()

and remove the # from it.

now it is working in Mozilla and IE.

Thanks All

Author: navin         Company URL: http://www.dotnetspark.com
Posted Date: May 07, 2013

Hi,

This is an excellent post.

So to take it further, how can we delete multiple records in the gridview, with the same method?

Please help.

Thanks,
Navin

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend