GridViewRow仅选择最后一行

时间:2014-04-17 17:35:25

标签: c# asp.net gridview gridviewrow

我尝试添加GridView,并在最后一列添加了一个按钮。它没有做任何事情我已经制作了一个新标签,看看它是否返回了任何数据,但它似乎只是在最后一行。 你看到我的代码有什么问题吗?提前谢谢!

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";
        }
    }

再次感谢你!

1 个答案:

答案 0 :(得分:1)

您的foreach循环正在执行,直到到达最后一列并覆盖标签文本。当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";
    }
}