1. 程式人生 > 實用技巧 >C#學習筆記(20140909)-按鈕控制元件:單擊事件和command事件

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
    事件並在事件中編寫相應程式碼,示例程式碼如下所示:

protectedvoidButton1_Command(objectsender,CommandEventArgse)
{
if(e.CommandName=="Show")//如果CommandNmae屬性的值為Show,則執行下面程式碼
{
Label1.Text=e.CommandArgument.ToString();//CommandArgument屬性的值賦值給Label1
}
}

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

綜上所述:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespaceWebApplication1
{
publicpartialclassWebForm1:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{

}

protectedvoidButton1_Click(objectsender,EventArgse)
{
Label1.Text="你點選了按鈕";
}

protectedvoidImageButton1_Click(objectsender,ImageClickEventArgse)
{
Label1.Text="你點選了圖片按鈕";
}

protectedvoidLinkButton1_Click(objectsender,EventArgse)
{
Label1.Text="你點選了連結按鈕";
}

protectedvoidButton1_Command(objectsender,CommandEventArgse)
{
if(e.CommandName=="show")
{
Label1.Text=e.CommandArgument.ToString();
}

}
}
}

wKioL1QPJL7hAZpbAAD2bRt0dp4409.jpg



轉載於:https://blog.51cto.com/felix520wj/1550376