Ebikeneser
Ebikeneser

Reputation: 2364

Get ID in GridView from checkBox

I have the following GridView -

<ItemTemplate>

         <asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="checkButton_OnClick"  AutoPostBack="true"/>

     </ItemTemplate>

  </asp:TemplateField>

        <asp:BoundField HeaderText="tID" DataField="tID" 
                        SortExpression="tID" HeaderStyle-CssClass = "hideGridColumn" ItemStyle-CssClass="hideGridColumn"></asp:BoundField>
        <asp:BoundField HeaderText="Name" HeaderStyle-HorizontalAlign=Center DataField="NAME" 
                        SortExpression="NAME" ItemStyle-HorizontalAlign=Center></asp:BoundField>

    </Columns>

Then find the rows where the checkBoxes are checked by -

 foreach (GridViewRow gvr in table_example.Rows)
        {
            if (((CheckBox)gvr.FindControl("CheckBox1")).Checked == true)
            {
                //Here I need the tID of the row that is checked


                WebService1 ws = new WebService1();
                ws.addID(tID);
            }
        }

I need to acquire the tID of the checked row, I tried -

int tID = gvr.cells["tID"];

However this did not work.

Upvotes: 0

Views: 2656

Answers (3)

felix Antony
felix Antony

Reputation: 1460

there is no need for this looping on the checkButton_OnClick event you van write the code as follows:

protected void checkButton_OnClick (object sender, EventArgs e)
    {
        CheckBox chk= (CheckBox)sender;
        GridViewRow gridViewRow = (GridViewRow)chk.NamingContainer;
        int rowindex = gridViewRow.RowIndex;
    }

Upvotes: 0

sp_m
sp_m

Reputation: 2707

foreach (GridViewRow gvr in table_example.Rows)
        {
            if (((CheckBox)gvr.FindControl("CheckBox1")).Checked == true)
            {
                //Here I need the tID of the row that is checked

int tID = Convert.ToInt32(gvr.Cells[1].Text);
                WebService1 ws = new WebService1();
                ws.addID(tID);
            }
        }

Try this one.

Upvotes: 0

lockdown87
lockdown87

Reputation: 13

To get the current row ID you'll do this: gvr.ID. But I'm not sure if you really wanna work with row ID or index. I guess you're looking for something like this (considering the index 1 refers to "tID" BoundField): gvr.Cells[1].Text.

Upvotes: 1

Related Questions