How to get id from gridview from chechbox.checked?

I have a gridview and button as follows. Then I bind gridview to the data from my database. GridView has two hidden fields for Id and ClassIndex. when I check the box and click the button, I want to get the corresponding identifier and file_name.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="check" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

and Button Like

 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send Request" /> 

code by button

 protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { var check = row.FindControl("check") as CheckBox; if (check.Checked) { int Id = Convert.ToInt32(row.Cells[1].Text); //some logic follws here } } } 

but I get an error like

The input string was not in the correct format. What is the mistake and how to solve it?

enter image description here

+5
source share
1 answer

Your loop is right.

But you forgot to notice one thing here, when you wanted to access the CheckBox , you did FindControl on row . This means that you are trying to find some control on this line.

Then why do you access the HiddenField control inside the row using row.Cell[1].Text ?
Try to find it too.

int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);

+2
source

Source: https://habr.com/ru/post/1239550/


All Articles