0

I'm trying to add a GridView and I've added a button to the last column. It wasn't doing anything and I've made a new label to see if its returning any data but it only seems to be working on the last row. Do you see anything wrong with my code? Thanks in advance!

HTML

                <asp:Button runat="server" Text="Submit" OnClick="ButtonClick8"  />
                 </ItemTemplate>
            </asp:TemplateField> 

        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <RowStyle BackColor="White" ForeColor="#330099" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <SortedAscendingCellStyle BackColor="#FEFCEB" />
        <SortedAscendingHeaderStyle BackColor="#AF0101" />
        <SortedDescendingCellStyle BackColor="#F6F0C0" />
        <SortedDescendingHeaderStyle BackColor="#7E0000" />
    </asp:GridView>

C#

    protected void ButtonClick8(object sender, System.EventArgs e)
{
    Button button2 = (Button)sender;

    GridViewRow row2 = (GridViewRow)button2.NamingContainer;
    int i = 0;
    int string1;
    foreach (GridViewRow gvr in GridView2.Rows)
    {
        if (gvr == row2)
        {
            string1 = Convert.ToInt32(gvr.Cells[0].Text);
            Label1.Text = string1.ToString();

        }
        else 
        {
            Label1.Text = "no";
        }
    }

Again thank you!

user3437235
  • 92
  • 3
  • 9

1 Answers1

1

Your foreach loop is executing until reaching last column and overriding the label text. Exit the loop when gvr == row2:

foreach (GridViewRow gvr in GridView2.Rows)
{
    if (gvr == row2)
    {
        string1 = Convert.ToInt32(gvr.Cells[0].Text);
        Label1.Text = string1.ToString();
        break;

    }
    else 
    {
        Label1.Text = "no";
    }
}
afzalulh
  • 7,925
  • 2
  • 26
  • 37