从后面的代码中获取 table 中一行的索引

Get the index of a row in a table from code behind

我有一个两列多行的table,第一列有名称,第二列有按钮,当我点击任何按钮时,如何获取按钮旁边的名称。

名字将从数据库中获取,按钮将根据我在数据库中的名字数量从后面的代码生成。

假设我有这个:

<asp:table runat="server" id="table1">
    <tr><td>Name1</td><td><asp:Button runat="server" Text="Save"/></td></tr>
    <tr><td>Name2</td><td><asp:Button runat="server" Text="Save"/></td></tr>
    <tr><td>Name3</td><td><asp:Button runat="server" Text="Save"/></td></tr>
 </asp:table>

我怎么知道按钮旁边是哪个名称,当我单击其中任何一个按钮时,我想获取该名称以便将其保存在数据库中。

为您的设计器代码使用与此类似的内容:

<asp:GridView ID="GridView" runat="server" OnRowCommand="gvUsers_RowCommand" AutoGenerateColumns="True">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="detail_LB" runat="server" Text="Detail" CommandName="Detail_LB" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

请注意 OnRowCommand,对于 LinkBut​​ton,请注意 CommandNameCommandArgument。该参数包含您单击按钮的行号。

在你后面的代码中:

    protected async void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Detail_LB")
        {
            //index contains the row number
            int index = Convert.ToInt32(e.CommandArgument);
            //get text in the cell next to the button
            string text = gvUsers.Rows[index].Cells[0].Text;
        }
    }

希望这有助于您了解如何使用表格。