共用方式為


HOW TO:回應 GridView 控制項中的按鈕事件

更新:2007 年 11 月

按一下 GridView 控制項中的按鈕時,會引發 RowCommand 事件。GridView 控制項具有內建功能,可進行編輯、刪除和分頁等作業。您也可以加入按鈕,並使用 RowCommand 事件加入自訂功能到控制項。

將自訂功能加入到 GridView 控制項的方式如下:

您可以在事件處理常式方法中使用事件引數的 CommandName 屬性來識別按鈕的功能。如果您使用 ButtonFieldTemplateField 物件,則也可以使用 CommandArgument 屬性識別目前的資料列。當您使用 ButtonField 物件時,CommandArgument 屬性會自動設定為資料列索引。當您使用 TemplateField 物件時,控制項不會自動設定 CommandArgument 屬性。在此情況下,如果要在事件處理常式中判斷資料列索引,可以使用資料繫結運算式,以便將按鈕的 CommandArgument 屬性設定為資料列索引。

若要回應 GridView 控制項中的按鈕事件

  1. 將按鈕的 CommandName 屬性設定為可識別其功能的字串,例如 "Print" 或 "Copy"。

  2. 如果您使用 TemplateField 物件,而必須存取事件處理常式方法中的資料列索引,請將按鈕的 CommandArgument 屬性設定為識別目前資料列的運算式。

    下列範例顯示如何將 TemplateField 資料行中按鈕的 CommandArgument 屬性設定為目前資料列索引。在範例中,資料行包含顯示購物車的 Button 控制項。

    <asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="AddButton"  
          CommandName="AddToCart" 
          CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
          Text="Add to Cart" />
      </ItemTemplate> 
    </asp:TemplateField>
    
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="AddButton"  
          CommandName="AddToCart" 
          CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
          Text="Add to Cart" />
      </ItemTemplate> 
    </asp:TemplateField>
    
  3. 建立 GridView 控制項之 RowCommand 事件的方法。請在方法中進行以下步驟:

    1. 檢查事件引數物件的 CommandName 屬性,來檢視傳遞的字串為何。

    2. 視需要使用 CommandArgument 屬性,以擷取包含按鈕之資料列的索引。

    3. 依照使用者按下的按鈕執行適當邏輯。

    下列範例說明如何在 GridView 控制項中按一下按鈕時進行回應。在範例中,TemplateField 資料行中的按鈕會傳送命令 "AddToCart"。RowCommand 事件處理常式會判斷按了哪個按鈕。如果是購物車按鈕,程式碼就會執行適當的邏輯。

    Protected Sub GridView1_RowCommand(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
      If (e.CommandName = "AddToCart") Then
        ' Retrieve the row index stored in the CommandArgument property.
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    
        ' Retrieve the row that contains the button 
        ' from the Rows collection.
        Dim row As GridViewRow = GridView1.Rows(index)
    
        ' Add code here to add the item to the shopping cart.
    
      End If
    End Sub
    
    protected void GridView1_RowCommand(object sender, 
      GridViewCommandEventArgs e)
    {
      if (e.CommandName == "AddToCart")
      {
        // Retrieve the row index stored in the 
        // CommandArgument property.
        int index = Convert.ToInt32(e.CommandArgument);
    
        // Retrieve the row that contains the button 
        // from the Rows collection.
        GridViewRow row = GridView1.Rows[index];
    
        // Add code here to add the item to the shopping cart.
      }
    
      }
    

    如需使用 ButtonField 類別的範例,請參閱 GridView.RowCommand 事件文件。

請參閱

工作

HOW TO:回應 DataList 或 Repeater 項目中的按鈕事件

參考

GridView Web 伺服器控制項概觀