Asp.net

ASP.NET + GridView + CommandField 作為 TemplateField

  • April 11, 2012

我有一個 GridView。我的 GridView 有一列包含“選項”列。此列包括傳統的 CommandField 選項(編輯、刪除等)。當使用 CommandField 時,我的程式碼設置可以工作。但是,我需要做一些自定義格式,所以我需要將 CommandField 轉換為 TemplateField。

我的問題是,如何從 TemplateField 中的各種 LinkBut​​ton 元素觸發 OnRowCommand、OnRowEditing、OnRowDeleting 和 OnRowUpdating 事件?

謝謝!

您所要做的就是將模板列內 LinkBut​​ton 的 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>

引用自:https://stackoverflow.com/questions/1647428