Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Id from Gridview of Chechbox.checked?

I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex. when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.

<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" />

the code behind button is

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 am getting an error like

Input string was not in a correct format. What is the error and how to solve it?

enter image description here

like image 333
Ritz Avatar asked Oct 31 '22 12:10

Ritz


1 Answers

Your looping correct.

But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.

Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.

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

like image 83
Bharadwaj Avatar answered Nov 15 '22 06:11

Bharadwaj