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

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

Compartir

Comentarios (15)

  • 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

Animate deja un comentario!!!

Eres un humano?

Últimos Tweets

Contáctanos

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

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

  • Email: info@developerji.com