GridView模板之處理模板中的事件

來源:互聯網
上載者:User
      有時候你可能會需要響應那些由模板列中的控制項產生的事件。例如你修改了前面樣本中的代碼,不使用靜態表徵圖而是用ImageButton控制項建立一組可單擊的圖片連結:
                     <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server" 
                      ImageUrl='<%# GetStatusPicture(Container.DataItem) %>' />
                 </ItemTemplate>
                </asp:TemplateField>

      
      問題是在模板中加入一個控制項後,GridView為每個資料項目建立一個該控制項的副本。這樣當單擊ImageButton控制項時,你需要通過這種方式確定被單擊的圖片屬於哪一行
      解決這一問題的辦法是使用GridView的事件而不是按鈕事件。GridView.RowCommand事件就是起這個作用的,因為它在模板中的任意按鈕被單擊時發生。模板中的控制項事件變成包含控制項中的事件的過程叫做事件冒泡。
      當然,你還是要藉助某種方式向RowCommand事件傳遞資訊以識別事件究竟發生在哪一行。奧妙在於所有按鈕控制項的兩個字串屬性:CommandName和CommandArgument。你可以為CommandName設定一個描述性的名字從而區分當前的單擊時發生在ImageButton上還是GridView中的其他按鈕上。CommandArgument提供一段與行有關的資訊,通過它你可以區分被單擊的行。可以通過資料繫結運算式提供這一資訊。
     下面是修改過的ImageButton標記:
      

              <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server" 
                      ImageUrl='<%# GetStatusPicture(Container.DataItem) %>'                      
                      CommandName="StatusClick"                      
                      CommandArgument='<%# Eval("ProductID") %>'
                     />
                 </ItemTemplate>
              </asp:TemplateField>

      下面是響應ImageButton單擊所需要的代碼:
      

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "StatusClick")
            lblInfo.Text = "You clicked product #" + e.CommandArgument;
    }

      這兒只是簡單的在一個標記上顯示ProductID

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.