Cómo eliminar registros de un GridView usando ASP.Net Ajax y jQuery

Cómo eliminar registros de un GridView usando ASP.Net Ajax y jQuery

En este artículo te mostrare como eliminar filas de un GridView mediante Ajax utilizando jQuery y ASP.NET. EL gridview se alimentara de una base de datos y cuando demos clic en eliminar, el registro se borrara de la base de datos.

Primero debemos crear una tabla Empleados en la base de datos

CREATE TABLE tbl_Emp(Empid int NULL,EmpName varchar(250) NULL, Gender varchar(20), EmpAddress varchar(500) NULL,City varchar(250) NULL,Salary int NULL, Fk_DepId int)

Insertas unos registros de prueba

INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(1, 'Jitendra' , 'Male', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(2, 'Aman' , 'Male', 'Demo Address', 'Ghaziabad', 0, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(3, 'Niman' , 'Male', 'Demo Address', 'Agra', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(4, 'Rita' , 'Female', 'Demo Address', 'Mathura', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(5, 'Sita' , 'Female', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(6, 'Rohan' , 'Male', 'Demo Address', 'Agra', 5000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(7, 'Sohan' , 'Male', 'Demo Address', 'Noida', 4000, 1)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(8, 'Mohan' , 'Male', 'Demo Address', 'Agra', 4000, 5)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(9, 'Ram' , 'Male', 'Demo Address', 'Noida', 5000, 1)

Después de crear la tabla e insertar los registros, creas la aplicación en el Visual Studio. Nuevo -> Sitio Web.

eliminar registros sql mediante ajax

A continuación, creas un nuevo elemento, agregas la nueva página.

eliminar filas gridview mediante jquery ajax

El HTML de la página queda de la siguiente manera.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Prueba.aspx.vb" Inherits="Demos.Prueba" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link href="css/style.css" rel="stylesheet" />
    <form id="form1" runat="server">
        <asp:GridView ID="gridEmpleados" runat="server" AutoGenerateColumns="false" >
                    <asp:BoundField HeaderText="EmpId" DataField="EmpId" />  
                    <asp:BoundField HeaderText="EmpName" DataField="EmpName" />  
                    <asp:BoundField HeaderText="Gender" DataField="Gender" />  
                    <asp:BoundField HeaderText="EmpAddress" DataField="EmpAddress" />  
                    <asp:TemplateField HeaderText="Herramientas">  
                            <asp:HiddenField ID="hdnEmpId" runat="server" Value='<%#Eval("EmpId") %>'></asp:HiddenField>  
                            <asp:LinkButton ID="btnDelete" Text="Delete Emp" runat="server" OnClientClick="return DeleteConfirmbox(this.id);"></asp:LinkButton>  
                <HeaderStyle   CssClass="row header blue"/>   
            <RowStyle CssClass="row cell" />
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> 
    <script type="text/javascript">  
        var row
        function DeleteConfirmbox(val) {  
            // confirm meg check for delete  
            var result = confirm('Esta seguro que quiere eliminar el empleado?');  
            if (result) {  
              // this is for get hdnvalue id  
                var value = val.replace("btnDelete", "hdnEmpId");  
                row = $("#" + val).closest("tr");
                    type: "POST",  
                    contentType: "application/json; charset=utf-8",  
                    url: "Prueba.aspx/BorrarInfo", // this for calling the web method function in cs code.  
                    data: '{empid: "' + $("#" + value).val() + '" }',// empid value                      
                    dataType: "json",  
                    success: OnSuccess,  
                    failure: function (data) {  
                        return false;
            return false;
        // function OnSuccess  
        function OnSuccess(response) {  
            if (response.d == 'true')  
                if ($("[id*=gridEmpleados] td").length == 0) {
                    $("[id*=gridEmpleados] tbody").append("<tr><td colspan = '4' align = 'center'>No records found.</td></tr>")
                alert("Empleado eliminado");
                return false;
            return false;

Por último el código del servidor queda de la siguiente forma:

Imports System.Data.SqlClient

Public Class Prueba
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        End If
    End Sub

    Public Sub LoadGrid()
        Dim con As New SqlConnection("data source=localhost;initial catalog=demos;UID=sa;PWD=SQL2008;")

        Dim cmd As New SqlCommand("Select * from tbl_Emp", con)
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        gridEmpleados.DataSource = ds
    End Sub

    Public Shared Function BorrarInfo(empid As Integer) As String
        Dim strmsg As String = String.Empty
        Dim con As New SqlConnection("data source=localhost;initial catalog=demos;UID=sa;PWD=SQL2008;")
        Dim cmd As New SqlCommand("delete from tbl_Emp where EmpId= @Empid", con)
        cmd.Parameters.AddWithValue("@Empid", empid)
        Dim retval As Integer = cmd.ExecuteNonQuery()
        If retval = 1 Then
            strmsg = "true"
            strmsg = "false"
        End If
        Return strmsg
    End Function

End Class


Comentarios (24)

  • Willey Responder

    Oh my goodness! Awesome article dude! Thank you, However I am experiencing troubles with your RSS. I don't know the reason why I am unable to subscribe to it. Is there anybody having the same RSS issues? Anybody who knows the solution will you kindly respond? Thanx!!

    Wednesday, July 12, 2017 1:11 AM
  • Miner Responder

    Hi there to every single one, it's truly a pleasant for me to pay a visit this site, it consists of valuable Information.

    Friday, July 14, 2017 2:51 PM
  • Moorman Responder

    Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

    Sunday, July 16, 2017 11:13 PM
  • Newsom Responder

    Howdy! I could have sworn I've been to this blog before but after going through some of the articles I realized it's new to me. Nonetheless, I'm certainly pleased I stumbled upon it and I'll be bookmarking it and checking back regularly!

    Friday, July 21, 2017 5:00 AM
  • Christian Responder

    Because the admin of this site is working, no hesitation very shortly it will be famous, due to its feature contents.

    Monday, July 31, 2017 4:37 PM
  • Lutz Responder

    Asking questions are truly good thing if you are not understanding something entirely, but this piece of writing provides pleasant understanding even.

    Thursday, August 31, 2017 10:56 PM
  • Burwell Responder

    We likewise have a committed info restoration group for QuickBooks information security.

    Monday, September 4, 2017 10:59 PM
  • Moffitt Responder

    I did not need bells and whistles and promptly upgraded my Quickbooks by the years as I up to date my laptop and OS as wanted.

    Wednesday, September 6, 2017 2:48 PM
  • Haskell Responder

    In the event you face any situation regarding billing call us at QuickBooks Help Cellphone Number.

    Thursday, September 7, 2017 10:04 AM
  • Stump Responder

    We can also recruit all kinds of janitorial level workers and security guards.

    Tuesday, September 12, 2017 6:31 AM
  • Mustar Responder

    What's up, yup this article is genuinely nice and I have learned lot of things from it on the topic of blogging. thanks.

    Tuesday, September 12, 2017 9:02 AM
  • Loy Responder

    I all the time used to read article in news papers but now as I am a user of web thus from now I am using net for posts, thanks to web.

    Tuesday, September 12, 2017 7:03 PM
  • Barker Responder

    Using modern techniques, the classical designs are reproduces to adapt to modern conditions.

    Wednesday, September 13, 2017 3:41 AM
  • Edge Responder

    Do you mind if I quote a few of your articles as long as I provide credit and sources back to your site? My blog site is in the exact same area of interest as yours and my visitors would really benefit from a lot of the information you provide here. Please let me know if this okay with you. Regards!

    Friday, September 15, 2017 11:39 AM
  • Samons Responder

    I've been surfing online more than three hours today, but I by no means found any attention-grabbing article like yours. It is pretty value sufficient for me. In my view, if all webmasters and bloggers made good content as you probably did, the web can be much more helpful than ever before.

    Monday, September 18, 2017 1:56 AM
  • Mullawirraburka Responder

    If you consider yourself a person with bold style, there are many different designs for a blazer that you might like.

    Sunday, September 24, 2017 6:36 PM
  • Villagomez Responder

    Many people report that there is little or no grease left on any of the parts when inspected.

    Wednesday, September 27, 2017 6:54 PM
  • Yarbrough Responder

    With havin so much content do you ever run into any problems of plagorism or copyright violation? My site has a lot of exclusive content I've either created myself or outsourced but it appears a lot of it is popping it up all over the web without my agreement. Do you know any solutions to help prevent content from being stolen? I'd certainly appreciate it.

    Monday, October 2, 2017 6:42 PM
  • Martins Responder

    Tem apropriado tempo tornar algumas planos para o futuro e é tempo para ser feliz. Tenho ler isto postar e se eu poderia eu quer sugerem você alguns deagarramento coisas ou conselhos . Talvez você pode escrever próxima artigos referindo este artigo. Eu quero ler ainda mais coisas aproximadamente isso!

    Tuesday, October 3, 2017 12:02 AM
  • Phelps Responder

    Thank you, I have just been looking for info about this topic for a while and yours is the best I've found out till now. But, what concerning the bottom line? Are you sure about the supply?

    Wednesday, October 4, 2017 2:24 PM
  • Clowes Responder

    His first book, published in 1967, was called Death at an Early Age.

    Sunday, October 8, 2017 3:30 PM
  • Baynes Responder

    Aluminum was the obvious choice, engineered for practical purposes, designed by real people.

    Friday, October 13, 2017 12:59 AM
  • Loche Responder

    Very good blog! Do you have any hints for aspiring writers? I'm planning to start my own site soon but I'm a little lost on everything. Would you recommend starting with a free platform like Wordpress or go for a paid option? There are so many choices out there that I'm completely overwhelmed .. Any ideas? Thanks!

    Friday, October 13, 2017 10:06 AM
  • Hendrickson Responder

    What i don't realize is in reality how you are no longer really much more well-preferred than you may be right now. You are so intelligent. You know therefore considerably in relation to this topic, produced me individually believe it from a lot of varied angles. Its like men and women don't seem to be involved until it is one thing to accomplish with Girl gaga! Your own stuffs nice. At all times deal with it up!

    Sunday, October 15, 2017 3:06 PM

Animate deja un comentario!!!

Eres un humano?

Últimos Tweets


  • Dirección: Plutarco Elias Calles 243, Granjas México, Iztacalco, DF.

  • Teléfono:55-2712-3820 o 55-4164-9484

  • Email: info@developerji.com