简体   繁体   中英

asp.net gridview: How can I have multiple button fields in one column?

I need to create multiple actions for a gridview - say, "Approve", "Deny", and "Return".

I can do this by creating a button field for each action:

<asp:ButtonField ButtonType="Link" CommandName="Approve" Text="Approve" /> 
<asp:ButtonField ButtonType="Link" CommandName="Deny" Text="Deny /> 
<asp:ButtonField ButtonType="Link" CommandName="Return" Text="Deny" /> 

However, this creates one column for each button.

Is there a way to have the same functionality, but combine them into a single column?

Have you considered using an TemplateField ? Here is an example:

<asp:GridView ID="grdTest" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btnApprove" runat="server" CommandName="Approve" Text="Approve" />
                <asp:LinkButton ID="btnDeny" runat="server" CommandName="Deny" Text="Deny" />
                <asp:LinkButton ID="btnReturn" runat="server" CommandName="Return" Text="Return" />
            </ItemTemplate>                
        </asp:TemplateField>
    </Columns>
</asp:GridView>

You can then capture the commands the exact same way using OnRowCommand or do whatever you like. You have full control to make it behave how you need and not be bound by the built in functionality of using the regular predefined column types.

Try to put buttons into the <asp:TemplateField> instead:

<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton CommandName="Approve" Text="Approve" /> 
        <asp:LinkButton CommandName="Deny" Text="Deny /> 
        <asp:LinkButton CommandName="Return" Text="Deny" />
    </ItemTemplate>
</asp:TemplateField>

The solution is not to use ButtonField elements.

To accomplish what you want you will need to create a column as a TemplateField and define buttons as regular ASP.NET <asp:Button id="myButton" /> within TemplateField 's ItemTemplate or EditItemTemplate as appropriate for your UI.

You can handle Click events in the GridView_OnItemCommand() handler, where you can check e.CommandName to figure out exactly which button caused the event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM