如何根据asp.net GridView中的点击按钮获取行索引?

时间:2013-01-11 23:12:45

标签: asp.net gridview

我有一些记录的Gridview(1条记录= 1行)。

在每一行我都添加了一个按钮,用于从我的mysql db中删除此记录。

每一行都有相同的按钮。

问题是我需要知道点击按钮的行?我需要这个来获取行索引来获取该行中的记录的id。

我怎样才能以最简单的方式做到这一点?

的GridView:

        <asp:GridView ID="GridView1" runat="server" 
        CellPadding="6" EnableModelValidation="True" ForeColor="#333333" 
        GridLines="None" Caption="TWOJE WIZYTY" Font-Bold="True" 
        onrowcreated="GridView1_RowCreated" style="text-align: left">
        <AlternatingRowStyle BackColor="#AEAEAE" />
        <EditRowStyle BackColor="Blue" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#868686" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="Blue" ForeColor="#333333" HorizontalAlign="Center" />
        <RowStyle BackColor="#C7C7C7" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    </asp:GridView>

按钮添加如下:

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        Button b1 = new Button();
        b1.Text = "usuń";
        b1.OnClientClick = "return potwierdzenie()";
        b1.Click+=new EventHandler(b1_Click);
        TableCell cel = new TableCell();
        cel.Width = Unit.Pixel(180);
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[2].Text = "";
            e.Row.Cells.Add(cel);
        }
        else
        {
            //HERE IS MY BUTTON ADDED! *********************
            cel.Controls.Add(b1);
            cel.HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
            e.Row.Cells.Add(cel);
        }
    }

1 个答案:

答案 0 :(得分:7)

您可以使用按钮的NamingContainer属性获取GridViewRow。然后,您就拥有了查找其他控件所需的全部内容(例如,如果您使用TemplateFields,则使用ID控件。)

protected void button_Delete_click(Object sender, EventArgs e)
{
    Button btn = (Button) sender;
    GridViewRow row = (GridViewRow) btn.NamingContainer;
    // assuming you store the ID in a Hiddenield:
    Hiddenield hiddenID = (HiddenField) row.FindControl("HiddenID");
    int ID = int.Parse(hiddenID.Value);
    // delete the record
}

您还可以通过row-index获取row.RowIndex