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">
    <title></title>
    <link href="css/style.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gridEmpleados" runat="server" AutoGenerateColumns="false" >
            <Columns>  
                    <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">  
                        <ItemTemplate>  
                            <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>  
                        </ItemTemplate>  
                    </asp:TemplateField>  
                </Columns>  
                <HeaderStyle   CssClass="row header blue"/>   
            <RowStyle CssClass="row cell" />
        </asp:GridView>
    </div>
    </form>
    <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");
                $.ajax({  
                    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) {  
                        alert(data);
                        return false;
                    }  
  
                      
                });    
            }
            return false;
        }  
  
        // function OnSuccess  
        function OnSuccess(response) {  
            if (response.d == 'true')  
            {  
                row.remove();
                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;
        }  
    </script>   
</body>
</html>

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
            LoadGrid()
        End If
    End Sub

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

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

    <System.Web.Services.WebMethod>
    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)
        con.Open()
        cmd.Parameters.AddWithValue("@Empid", empid)
        Dim retval As Integer = cmd.ExecuteNonQuery()
        con.Close()
        If retval = 1 Then
            strmsg = "true"
        Else
            strmsg = "false"
        End If
        Return strmsg
    End Function

End Class

 

Artículos relacionados
21 Comentarios
  • Gustafson Comentar
    Friday, June 2, 2017

    It's really a cool and useful piece of information. I'm glad that you simply shared this helpful info with us. Please keep us up to date like this. Thank you for sharing.

  • Woodcock Comentar
    Friday, June 2, 2017

    It's very trouble-free to find out any topic on web as compared to textbooks, as I found this paragraph at this web site.

  • Reiner Comentar
    Tuesday, March 13, 2018

    Hey just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Opera. I'm not sure if this is a format issue or something to do with web browser compatibility but I figured I'd post to let you know. The style and design look great though! Hope you get the problem resolved soon. Many thanks

  • Hall Comentar
    Wednesday, March 14, 2018

    You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  • Ernst Comentar
    Friday, March 16, 2018

    Không ch? d?i ??i n? gi?i mà vùng kín c?a nam ?ung là khu v?c r?t nh?y ??m. Do dó nh?ng d?ng mà? râu ??n ph?i h?t s?c c?n tr?ng khi th?y ?uong v?t có mùi hôi, ng?a, ha? ti?t ra ??ch ??t thu?ng. Duong v?t ?ó mù? hôi, ng?a không ch? gây ra s? t? ti cho nam gi?? mà còn gây ra nhi?u ?nh hu?ng d?n ch?t lu?ng d?i ??ng tình d?c, cung nhu ??c kh?e c?a nam gi?i.

  • Carney Comentar
    Wednesday, March 21, 2018

    Estaria muy agradecida si me pudiesen enviar un presupuesto de llos extintores necesarios.

  • Lunsford Comentar
    Wednesday, March 21, 2018

    Cho cháu h?i Ð?i v?i TPHCM ch? nào ngan ng?a sùi mào gà Tuy?t nhiên nh?t ?? em Ð?i v?i t?n Bình Thu?n c?n em k n?m du?c ch? nào th?p d? di khám . AloBacsi có nguy co ch? giúp cháu du?c không ?? em c?m on AloBacsi m?t vài . (Thanh Nhan Nguyen) AloBacsi tr? l?i: Chào b?n, tru?c kia, sùi mào gà du?c xem là 1 b?nh lành tính. tuy nhiên hi?n t?i , nhi?u nhà phuong pháp cho r?ng trong nhi?u tru?ng h?p, b?nh lí th? hi?n chi?u hu?ng vuon lên là ác tính, gây ra ung thu c? t? cung ho?c th?ng nh? . l?a tu?i b? b?nh r?t nhi?u nh?t là 20-25. b?nh lý này thu?ng thông qua 2 nguyên do gây ra ra: + thông qua quan h? d?n ngu?i dã và dang dính b?nh . + vì gi?t k s?ch s?. + thông qua m?c chung d? v?i ngu?i dang m?c b?nh + b?ng ngu?n c?i nu?c b?n s? d?ng 0 ?n. v?i b?nh này b?n có kh? nang ki?m tra và ch?a t?i BV Da Li?u ho?c BV T? Du. Tùy m?c d? n?ng nh? c?a b?nh lý s? b?t d?u th?y gi?i pháp ch?a tr? phù h?p nhu: d?t di?n, ch?m thu?c. nh?t thi?t ph?i kiên trì ngan ch?n b?nh lý s? ngan ng?a kh?i, gi? d? d? lâu s? khó làm m?t phê duy?t b?nh nguy nguy hi?m s? lan tràn ra m?t vài mi?n khác trên kia thân xác . B?n có th? k?t n?i nh?ng phòng khám sau d? du?c xét nghi?m và ch?a k?p th?i di?m nhé: BV Da Li?u TPHCM 2 Nguy?n Thông, Phu?ng 6, Qu?n 3, TPHCM ÐT: 08 3930 5995 t?ng dài nóng: 0908 051 200 D?ch v? d?t l?ch h?n làm ki?m tra b?nh lý 0909 100 819 Ð? không m?c cò m?i d? d? trong khi d?n ki?m tra t?i BV Da Li?u b?n có kh? nang B? sung thêm bài vi?t sau d? ch? d?ng hon trong khi chuy?n di . >> quy trình xét nghi?m b?nh lý t?i BV Da Li?u TPHCM BV T? Du TPHCM 106 C?ng Qu?nh, Phu?ng Ph?m Ngu Lão, Qu?n 1, TPHCM ÐT: 08 5404 2829 Mong r?ng m?t vài thông tin trên kia s? còn giúp ích cho b?n. Thân ái,

  • Marion Comentar
    Friday, March 23, 2018

    Hello to all, the contents existing at this site are in fact remarkable for people experience, well, keep up the good work fellows.

  • Bastow Comentar
    Friday, March 23, 2018

    Hey there! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup. Do you have any methods to prevent hackers?

  • Zhang Comentar
    Sunday, March 25, 2018

    Cho tôi h?i ? TPHCM ch? nào tránh sùi mào gà Tuy?t d?i nh?t ?? tôi Ð?i v?i t?n Bình Thu?n ph?i em k hi?u bi?t ch? nào r? d? di khám. AloBacsi có nguy co ch? giúp cháu du?c 0 ?? cháu trân tr?ng c?m on AloBacsi m?t vài . (Thanh Nhan Nguyen) AloBacsi tr? l?i: Chào b?n, tru?c dây , sùi mào gà du?c xem là m?t b?nh lành tính. th? tuy nhiên hi?n t?i, m?t s? nhà h?p lý cho r?ng trong m?t s? n?u nhu , b?nh nguy nguy hi?m phát hi?n chi?u hu?ng tr? nên ác tính, gây ra ung thu c? t? cung ho?c b?u. l?a tu?i dính b?nh các d?c bi?t là 20-25. b?nh này thu?ng do 2 nguyên do gây ra: + vì giao c?u b?ng ngu?i dã và dang m?c b?nh . + ung chu?n r?a k s?ch s?. + phê duy?t m?c chung d? v?i ngu?i dang mang b?nh + do c?i ngu?n nu?c b?n dùng không ?n. kèm b?nh lý này b?n có khi tham khám và ngan ch?n t?i BV Da Li?u ho?c BV T? Du. Tùy th?i gian n?ng nh? c?a b?nh lý s? th?y hu?ng phòng tránh phù h?p nhu: d?t di?n, ch?m thu?c. b?t bu?c kiên trì ch?a b?nh nguy nguy hi?m s? làm h?t kh?i, n?u d? lâu s? khó ngan ng?a vì b?nh h?c s? lan r?ng ra nh?ng vùng khác trên toàn thân . B?n có nguy co liên l?c m?t s? tr?m xá sau d? du?c xem xét và ch?a k?p th?i nhé: BV Da Li?u TPHCM 2 Nguy?n Thông, Phu?ng 6, Qu?n 3, TPHCM ÐT: 08 3930 5995 s? di?n tho?i nóng: 0908 051 200 D?ch v? d?t l?ch h?n khám b?nh lý 0909 100 819 Ð? 0 m?c cò m?i d? d? lúc d?n ki?m tra tham khám t?i BV Da Li?u b?n có kh? nang B? sung thêm bài vi?t sau d? ch? d?ng hon khi di chuy?n . >> quá trình làm ki?m tra b?nh tình t?i BV Da Li?u TPHCM BV T? Du TPHCM 106 C?ng Qu?nh, Phu?ng Ph?m Ngu Lão, Qu?n 1, TPHCM ÐT: 08 5404 2829 Mong r?ng m?t vài tin t?c phía trên s? giúp d? ích cho b?n. Thân ái,

  • Vallecillo Comentar
    Sunday, March 25, 2018

    Howdy! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a wonderful job!

  • da Mata Comentar
    Wednesday, April 18, 2018

    Bom site, sou discordomais uma vez.

  • Lording Comentar
    Tuesday, April 24, 2018

    Hello there! This blog post couldn't be written any better! Reading through this post reminds me of my previous roommate! He constantly kept preaching about this. I most certainly will send this post to him. Fairly certain he'll have a great read. Thanks for sharing!

  • Labbe Comentar
    Saturday, April 28, 2018

    Pretty great post. I simply stumbled upon your weblog and wished to mention that I have truly enjoyed browsing your blog posts. After all I will be subscribing to your feed and I am hoping you write again soon!

  • Edkins Comentar
    Saturday, April 28, 2018

    My brother recommended I might like this web site. He was totally right. This post actually made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  • Valliere Comentar
    Monday, April 30, 2018

    Hello! Someone in my Facebook group shared this website with us so I came to take a look. I'm definitely loving the information. I'm bookmarking and will be tweeting this to my followers! Outstanding blog and brilliant design and style.

  • Hedgepeth Comentar
    Thursday, May 3, 2018

    Fascinating blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog stand out. Please let me know where you got your design. Cheers

  • Snoddy Comentar
    Thursday, May 3, 2018

    With havin so much written content do you ever run into any issues of plagorism or copyright violation? My website has a lot of exclusive content I've either created myself or outsourced but it seems a lot of it is popping it up all over the web without my authorization. Do you know any techniques to help reduce content from being stolen? I'd certainly appreciate it.

  • Crick Comentar
    Thursday, May 17, 2018

    My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on numerous websites for about a year and am concerned about switching to another platform. I have heard good things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any help would be greatly appreciated!

  • Manzo Comentar
    Saturday, May 19, 2018

    Good day I am so thrilled I found your weblog, I really found you by mistake, while I was looking on Yahoo for something else, Regardless I am here now and would just like to say cheers for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great jo.

  • Etienne Comentar
    Saturday, May 26, 2018

    If you are going for best contents like me, simply pay a visit this web page every day since it presents feature contents, thanks

Enviame un comentario