共用方式為


HOW TO:回應資料繫結控制項中的按鈕事件

更新:2007 年 11 月

如果使用搭配範本 (例如 DataListFormView 控制項) 的資料繫結控制項,而範本包含 ButtonLinkButtonImageButton Web 伺服器控制項,則按鈕就能夠將它們的 Click 事件轉寄給包含控制項。這可以讓您將資料繫結控制項尚未定義的自訂功能按鈕 (例如編輯、刪除、更新和取消) 都包含在內。

若要回應資料繫結控制項中的按鈕事件

  1. 在控制項範本中加入 ButtonLinkButtonImageButton

  2. 將按鈕的 CommandName 屬性設定為可識別功能的字串,例如 "sort" 或 "copy"。

  3. 建立控制項之 ItemCommand 事件的方法。請在方法中進行以下步驟:

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

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

    下列範例說明如何在 DataList 控制項中按一下按鈕時進行回應。在範例中,ItemTemplate 包含顯示購物車的 ImageButton 控制項。這個按鈕會傳送 AddToCart 命令。事件處理常式會判斷所按按鈕為何,如果是購物車按鈕的話,就會執行適當邏輯。

    Private Sub DataList1_ItemCommand(ByVal source As Object, _
            ByVal e As DataListCommandEventArgs) _
            Handles DataList1.ItemCommand
        If (e.CommandName = "AddToCart") Then
           ' Add code here to add the item to the shopping cart.
           ' Use the value of e.Item.ItemIndex to find the data row
           ' in the data source.
        End If
    End Sub
    
    private void DataList1_ItemCommand(object source, 
        DataListCommandEventArgs e)
    {
        if (e.CommandName == "AddToCart")
        {
            // Add code here to add the item to the shopping cart.
            // Use the value of e.Item.ItemIndex to find the data row
            // in the data source.
        }
    }
    

請參閱

工作

HOW TO:在 ASP.NET Web 網頁中建立事件處理常式 (Visual Studio)

概念

ASP.NET 資料繫結 Web 伺服器控制項概觀