将Button绑定到GridView

Tyl*_*eat 2 c# asp.net gridview button

这是一个非常简单的问题,我只是不确定如何做到这一点.我想将一个Button或者ImageButton绑定到ASP.NET/C#中的GridView.目前,GridView有两列,并绑定到一个包含两列的DataTable.我想在GridView中添加第三列,其中包括Button.

我知道GridView有ButtonField,但我不太清楚如何使用它来做我想做的事情.我想动态生成这些按钮并将它们添加到GridView.

以下是我的GridView现在的样子:

<asp:GridView 
    ID="GridView1"
    Runat="server">
    <Columns>
        <asp:HyperLinkField 
            HeaderText="Display Name"
            DataNavigateUrlFields="DISPNAME"
            DataNavigateUrlFormatString="ViewItem.aspx"
            DataTextField="DISPNAME">
            <ItemStyle Width="70%" />
        </asp:HyperLinkField>
        <asp:BoundField
            DataField="TypeDisp"
            HeaderText="Type">
            <ItemStyle Width="20%" />
        </asp:BoundField>
    </Columns>
 </asp:GridView>
Run Code Online (Sandbox Code Playgroud)

A_N*_*lsi 6

您可以使用如下模板字段,

<TemplateField>
    <ItemTemplate>
        <asp:ImageButton ImageUrl="image url" CommandName="SomeCommand" CommandArgument='<%# Eval("Id") %>'/>
    </ItemTemplate>
</TemplateField>
Run Code Online (Sandbox Code Playgroud)

然后你可以处理GridView的RowCommand事件并检查e.CommandName以查看要执行的命令,你也可以获得e.CommandArgument,这可能是我在上面代码中使用的行Id.