How to get the id of a row in GridView using a LinkButton?

0

How to get the id of a row when activating the LinkButton event ?, what I want to achieve is a delete query for sql server and get something like this;

protected void GridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    int userid ="obteniendo el ID de usuario de una fila particular para usar esta variable en la consulta"

    using (SqlConnection con = new SqlConnection((string)Session["conexion"]))
    {

        con.Open();
        SqlCommand cmd = new SqlCommand("Delete from ErrorLog where ID='" + userid + "'", con);
        result = cmd.ExecuteNonQuery();
        con.Close();
    }

}

The structure where I define the button is as follows:

 <ItemTemplate>
       <asp:LinkButton ID="LinkButton1"
        runat="server" CausesValidation="False"
        CommandName="Delete"
                    OnClientClick='return confirm("¿Estas seguro de querer eliminar esta fila?");'
             Text="Delete" />
        </ItemTemplate>
   </asp:TemplateField>
    
asked by KJSK 19.10.2018 в 03:08
source

1 answer

1

Look, I do it in another way. All my projects I have them like that.

On the grid I do the following:

 <asp:TemplateField HeaderText="" HeaderStyle-Width="1%" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                    <ItemTemplate>
                                        <div style="display:none">
                                            <asp:ImageButton ID="imgConfirmarPelotero" runat="server"
                                                CommandName="Confirmar" Visible="false"
                                                CommandArgument='<%#Container.DataItemIndex%>'
                                                ImageUrl="~/images/preguntaEliminar.png"
                                                ToolTip="Eliminar Relato" 
                                                Height="20px" Width="20px" ImageAlign="Middle" />

                                            <div style="display:none">
                                                <asp:ImageButton ID="imgEliminarPelotero" runat="server"
                                                CommandName="Borrar"
                                                CommandArgument='<%#Bind("ID")%>'
                                                ImageUrl="~/images/preguntaEliminar.png"
                                                ToolTip="Eliminar Pelotero" 
                                                Height="20px" Width="20px" ImageAlign="Middle" />
                                            </div>


                                            <asp:ImageButton ID="imgEditarPelotero" runat="server"
                                                CommandName="Editar"
                                                CommandArgument='<%#Bind("ID")%>'
                                                ImageUrl="~/images/edit.png"
                                                ToolTip="Editar Pelotero" Visible="false"
                                                Height="20px" Width="20px" ImageAlign="Middle" />
                                        </div>

                                    </ItemTemplate>
</asp:TemplateField>

Then in the backend I use the rowCommand event:

 protected void grdTags_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id;
                string script;
                Pelotero item = new Pelotero();

                switch (e.CommandName)
                {
                    case "Editar":
                        ID = Convert.ToInt32(e.CommandArgument);
                      // En la linea anterior ya tengo el id de mi elemento.
                      //Hago una consulta y Cargo mis datos para editarlo en un modal.
                        break;


                    case "Confirmar":


                      //Pido confirmación usando js.
                       int rowindex = Convert.ToInt32(e.CommandArgument);
                    var pagesize = this.grid.PageSize;
                    var pageindex = this.grid.PageIndex;
                    var paginatedRowIndex = rowindex - (pagesize * pageindex);

                    script = @"<script type='text/javascript'> ConfirmarEliminar('" + paginatedRowIndex + "')</script>";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "confirmacion", script, false);

                     //Mas adelante vas a ver en la funcion js, al ser confirmada 
                     //provoco un postback haciendo click en el boton restante y va derecho a "borrar"
                     break;
                    case "Borrar":
                        if (wsPeloteros.Delete(Convert.ToInt32(e.CommandArgument)).Result != 0)
                            FillGrid();
                        break;

                }
            }
            catch (Exception ex)
            { }
        }

Function to request confirmation and cause postback in js:

 function ConfirmarEliminar(id) {
            alertify.confirm("¿Confirma que desea eliminar la pregunta seleccionada?", function (e) {
                if (e) {

                    id = parseInt(id) + 2;
                    if (id < 10)
                        id = '0' + id;

                    document.getElementById('ctl00_ContentPlaceHolder1_grid_ctl' + id + '_btnEliminarPregunta').click();

                    return true;
                }
                else {
                    return false;
                }
            });
            TextoBotonCancel("No");
            TextoBotonOk("Si");
        }

The answer was half a long and I do not know if it is too clear, but any questions you ask me. Hope this can help you. Greetings!

    
answered by 19.10.2018 в 03:51