Search code examples
c#gridviewlabelitemtemplate

Gridview label template item value to delete a row


Good Afternoon. I have a programatically filled gridview, so i was wondering how could i get the values of a label in template items to delete that gridview row. I'm newby at ASP and c# so this may be easy but i want if you can help me.

So here is my code.

        <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
        <Columns>
            <asp:TemplateField HeaderText="ID UNIDAD">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="UNIDAD">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
               <asp:TemplateField HeaderText="FRACCIONES">
                <EditItemTemplate>
                    <asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
               <asp:TemplateField HeaderText="CLAVE SAT">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
          <asp:TemplateField ShowHeader="false">
              <EditItemTemplate>
                    <asp:ImageButton ID="LinkButton1" runat="server" title="Acttualizar" CausesValidation="True" CommandName="Update" Text="Actualizar" ImageUrl="~/assets/iconos/lapiz.ico"></asp:ImageButton>
                  <asp:ImageButton ID="LinkButton2" runat="server" title="Cancelar" CausesValidation="False" CommandName="Cancel" Text="Cancelar" ImageUrl="~/assets/iconos/volver.ico"></asp:ImageButton>
              </EditItemTemplate>
              <ItemTemplate>
                  <asp:ImageButton ID="LinkButton1" runat="server" title="Editar" CausesValidation="False" CommandName="Edit" Text="Editar" ImageUrl="~/assets/iconos/lapiz.ico"></asp:ImageButton>
                  <asp:ImageButton ID="LinkButton2" runat="server" title="Borrar" CausesValidation="False" CommandName="Delete" Text="Borrar" ImageUrl="~/assets/iconos/borrame.ico" OnClientClick="return confirm('¿Deseas Borrar el Registro?');" ></asp:ImageButton>

              </ItemTemplate>
              <FooterTemplate>
                   <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
              </FooterTemplate>
          </asp:TemplateField>






        </Columns>
        <FooterStyle BackColor="#CCCCCC" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
        <RowStyle BackColor="White" />
        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#808080" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#383838" />
    </asp:GridView>

Then here is my try to delete the row but with no results.

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    con.Open();

    int unid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());

    query = "delete from unidades where id_unidad ="+unid+"";
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.ExecuteNonQuery();
    con.Close();
    llenagrid();
    IncrementoID();


    Response.Write("<script>alert('Registro Borrado')</script>");

}

I tried with the sender items, with the e.rows, and some codes i tried but none of them worked for me, so any way to make it work to delete the row from the gridview and database?


Solution

  • first in your Gridview add row data bound like this for selection

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                try
                {
    
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                         e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
    
                    }                            
                }
                catch (Exception ex)
                {
    
                }
            }
    

    and now get label text or textbox text like this

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
           //if you want to get label text from gridview then do like this
          System.Web.UI.WebControls.label lbl = ((System.Web.UI.WebControls.label)GridView1.SelectedRow.Cells[0].FindControl("LabelID"));//put lebelid here
          string labelText = lbl.Text;
    
          // if you want to get textbox text from gridview then do like this
            System.Web.UI.WebControls.TextBox txt = ((System.Web.UI.WebControls.TextBox)gvTest.SelectedRow.Cells[0].FindControl("TextboxID"));//put textboxID here
             string textBoxText = txt.Text;                      
             //your code Here    
    }