ASP.NET + GridView + CommandField 作为模板字段
-
22-07-2019 - |
题
我有一个网格视图。我的 GridView 有一个包含“选项”列的列。此列包括传统的 CommandField 选项(编辑、删除等)。我的代码设置可以在使用 CommandField 时工作。但是,我需要进行一些自定义格式设置,因此我需要将 CommandField 转换为 TemplateField。
我的问题是,如何从 TemplateField 中的各个 LinkButton 元素触发 OnRowCommand、OnRowEditing、OnRowDeleting 和 OnRowUpdating 事件?
谢谢你!
解决方案
您所要做的就是将模板列内 LinkButton 的 CommandName 属性设置为“编辑”以进行编辑,“删除”以进行删除,“更新”以进行更新。这将分别触发 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" />
<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”
切换到源并自动添加代码。
不隶属于 StackOverflow