ASP.NET + GridView + CommandField为TemplateField

我有一个GridView。我的GridView有一个包含“选项”列的列。此列包括传统的CommandField选项(编辑,删除等)。我使用CommandField时可以使用代码设置。但是,我需要做一些自定义格式化,所以我需要将CommandField转换为TemplateField。 我的问题是,如何从TemplateField中的各种LinkBut​​ton元素触发OnRowCommand,OnRowEditing,OnRowDeleting和OnRowUpdating事件? 谢谢!     
已邀请:
您所要做的就是将模板列中LinkBut​​ton的CommandName属性设置为“Edit”进行编辑,“Delete”进行删除,将“Update”进行更新。这将分别触发GridView RowEditing,RowDeleting和RowUpdating事件。要触发RowCommand事件,您需要设置GridView控件的OnRowCommand属性。
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand"
    OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
    OnRowUpdating="GridView1_RowUpdating">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <!--To fire the OnRowEditing event.-->
            <asp:LinkButton ID="lbEdit" runat="server" CommandName="Edit" 
                Text="Edit">
            </asp:LinkButton>
            <!--To fire the OnRowDeleting event.-->
            <asp:LinkButton ID="lbDelete" runat="server" CommandName="Delete" 
                Text="Delete">
            </asp:LinkButton>
            <!--To fire the OnRowUpdating event.-->
            <asp:LinkButton ID="lbUpdate" runat="server" CommandName="Update" 
                Text="Update">
            </asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>    
</asp:GridView>
    
我有同样的问题。 为了编辑,我做了以下事情:
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="EditButton"
                                runat="server"
                                CommandName="Edit" 
                                Text="Edit" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="UpdateButton"
                                runat="server"
                                CommandName="Update"
                                Text="Update" />&nbsp;
                <asp:LinkButton ID="Cancel"
                                runat="server"
                                CommandName="Cancel"
                                Text="Cancel" />
            </EditItemTemplate>
        </asp:TemplateField>
这允许显示/隐藏更新和取消按钮。 至于删除,我使用了以下内容:
    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="DeleteButton"
                            Text="Delete"
                            CommandName="Delete" 
                            runat="server" />
        </ItemTemplate>
    </asp:TemplateField>
    
单击属性中的列,添加
CommandField(Edit,update,Cancel)
并单击“将此字段转换为templateField” Swich to Source并自动添加代码。     

要回复问题请先登录注册