Hiddenfield value always zero

Asked

Viewed 33 times

1

Good morning, I am learning Asp.net and I came across a problem in my code that I do not know how to solve. I have a gridview that is fed by the database and I have a button that calls the Rowdeleting event and I’m trying to get the value of Hiddenfield from the same Row where this event was called, sorry if it got confused if you don’t understand I can try to explain better.

This is my code:

<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false" EmptyDataText="No data available" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" CssClass="table table-bordered">
    <Columns>
        <asp:TemplateField HeaderText="Role">  
            <ItemTemplate>                                      
                <asp:HiddenField ID="hiddenid" runat="server" Value='<%#Eval("id") %>' />
                <asp:Label ID="lbl_Role" runat="server" Text='<%#Eval("Role") %>' ReadOnly="true"></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:TextBox ID="txt_Role" runat="server" Text='<%#Bind("Role") %>'></asp:TextBox>  
            </EditItemTemplate>  
        </asp:TemplateField> 
        <asp:CommandField ItemStyle-HorizontalAlign="Right" ItemStyle-Width="5" EditText="<img class='img-fluid' style='min-width: 20px; max-width: 20px;' src='imagens/edit.svg'>" ShowEditButton="true" />
        <asp:CommandField ItemStyle-HorizontalAlign="Right" ItemStyle-Width="5" DeleteText="<img class='img-fluid' style='min-width: 20px; max-width: 20px;' src='imagens/recyclebin-512.png'>" ShowDeleteButton="True" />
    </Columns> 
</asp:GridView>

Code-Behind:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    string _id = "";
    int _index = Convert.ToInt32(e.RowIndex);

    foreach (GridViewRow row in GridView1.Rows)
    {
        if (_index == row.RowIndex)
        {
            _id = row.Cells[0].Text;
        }
    }

    DataTable dt = _sql.GetEditRoles();
    GridView1.DataSource = dt;
    GridView1.DataBind();

}

The value that is coming empty is _id.

Thank you very much!

2 answers

1


I believe that the .Text will not get value from an Hidden field.

An alternative is to use this column as a Datakey.

<asp:GridView DataKeyNames="id" ...

In the event you need to use:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    var key = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
}
  • Thank you very much Ronaldo!

0

To get the value of HiddenField need to go through the property Value:

if (_index == row.RowIndex)
{
    _id = ((HiddenField)row.Cells[0].FindControl("hiddenid")).Value;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.