C#學習筆記(20140909)-按鈕控件:單擊事件和command事件

    在 Web 應用程序和用戶交互時,常常需要提交表單、獲取表單信息等操作。在這其間,按鈕控件
是非常必要的。按鈕控件能夠觸發事件,或者將網頁中的信息回傳給服務器。在 ASP.NET 中,包含三
類按鈕控件,分別爲 Button、LinkButton、ImageButton。


  1. Click 單擊事件

    在Click 單擊事件中,通常用於編寫用戶單擊按鈕時所需要執行的事件,這種事件很簡單,用戶單擊一個按鈕,就會執行按鈕中的代碼。


  2. Command 命令事件

    按鈕控件中,Click 事件並不能傳遞參數,所以處理的事件相對簡單。而Command 事件可以傳遞參
    數,負責傳遞參數的是按鈕控件的 CommandArgument 和 CommandName 屬性。

    wKiom1QPI0jCclrwAADiTu5I-iQ659.jpg

    CommandArgument 和 CommandName 屬性

        將CommandArgument和CommandName屬性分別設置爲Hello!和Show , 單擊 創建一個Command
    事件並在事件中編寫相應代碼,示例代碼如下所示:

    protected void Button1_Command(object sender, CommandEventArgs e)    
    {
    if (e.CommandName == "Show") //如果 CommandNmae 屬性的值爲 Show,則運行下面代碼
    {
    Label1.Text = e.CommandArgument.ToString();//CommandArgument 屬性的值賦值給 Label1
    }
    }

    Command 有一些 Click 不具備的好處,就是傳遞參數。可以對按鈕的 CommandArgument 和
CommandName 屬性分別設置, 通過判斷 CommandArgument 和 CommandName 屬性來執行相應的方法 。
這樣一個按鈕控件就能夠實現不同的方法,使得多個按鈕與一個處理代碼關聯或者一個按鈕根據不同的
值進行不同的處理和響應。相比 Click 單擊事件而言,Command 命令事件具有更高的可控性。

    綜上所述:

    using System;    
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                Label1.Text = "你點擊了按鈕";
            }
    
            protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
            {
                Label1.Text = "你點擊了圖片按鈕";
            }
    
            protected void LinkButton1_Click(object sender, EventArgs e)
            {
                Label1.Text = "你點擊了鏈接按鈕";
            }
    
            protected void Button1_Command(object sender, CommandEventArgs e)
            {
                if (e.CommandName=="show")
                {
                    Label1.Text = e.CommandArgument.ToString(); 
                }
    
            }
        }
    }

wKioL1QPJL7hAZpbAAD2bRt0dp4409.jpg



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章