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

3

我有一个Gridview,其中包含一些记录(1个记录=1行)。

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

每一行都有相同的按钮。

问题是我需要知道点击的按钮在哪一行? 我需要这个来获取行索引以获取该行中的记录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);
        }
    }

你能否在问题中更新一下你在 GridView 中使用的标记?根据你声明按钮的方式不同,解决方案可能也会有所不同。 - undefined
记录的ID在哪里?你是用C#还是VB.NET? - undefined
请查看此问题的第一个答案,以获取一些想法 - 希望这能帮到你。 - undefined
1个回答

9
你可以使用按钮的 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.RowIndex获取row-index

@PawełAdamczyk: 既然你现在编辑了问题并显示你不使用模板字段,那么你就不能使用FindControl。但是你可以使用row.RowIndex来获取索引,如果有帮助的话。(编辑我的答案)。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接