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">
    <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 (5)

  • 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

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