OnClick和OnCommand的區別

來源:互聯網
上載者:User

<asp:Button ID="Button1" runar="server" OnClick="Button1_Click" OnCommand="Button1_Command">

同時定義了OnClick和OnCommand,
在代碼中定義相關事件

Button1_Click(object sender,EventArgs e){}

Button1_Command(object sender,CommandEventArgs e){}

1、單擊Button會同時觸發這兩個事件,但先執行Click,後執行Command

2、不同之處

Command可以通過設定CommandName和CommandArgument來區分不同的Button,
可通過包含事件數目據的CommandEventArgs來擷取或設定

而Click中,也可以擷取CommandName和CommandArgument,通過(Button)sender這種形式。

例子:OnClick
<asp:Button ID="Button1" runar="server" OnClick="Button1_Click" CommandName="A" Text="A">
<asp:Button ID="Button2" runar="server" OnClick="Button1_Click" CommandName="B" Text="B">
<asp:Button ID="Button3" runar="server" OnClick="Button1_Click" CommandName="C" Text="C">
定義一個Button1_Click(object sender,EventArgs e){}就夠了,
其它需要用(Button)sender.CommandName來確定是哪一個Button。

換成OnCommand道理一樣,不同之外是用e.CommandName就可以確定。

(在ASP.NET2.0中,事件註冊也可以省略)

3、這兩種方法均為伺服器端事件,如果需要增加用戶端事件,需要通過用Attributes來對Button進行onclick的用戶端事件的設定,如:
Button1.Attributes.Add("onclick","yourfunction();")
同時可以在aspx頁面中定義yourfunction()方法。

4、關於TextBox1.Attributes.Add的問題

---問題---------
我的頁面上分別有兩個按鈕Button1,Button2,和兩個編輯框TextBox1,TextBox2,我在PAGE_LOAD裡加上下面這行代碼後,  
   
TextBox1.Attributes.Add("onkeydown","if(event.keyCode==13){document.all.Button1.click();}");  
   
實現了對TextBox1進行編輯的時候敲ENDER直接執行Button1.click的代碼,但是我發現這時候對  
TextBox2進行編輯的時候敲ENDER也會直接執行Button1.click的代碼.  
   
於是我又在PAGE_LOAD裡加上  
   
TextBox2.Attributes.Add("onkeydown","if(event.keyCode==13){document.all.Button2.click();}");  
   
但是對TextBox2進行編輯的時候敲ENDER仍然會直接執行Button1.click的代碼.而不執行Button2.click的代碼  
   
而且現在即使我把這兩條語句刪除掉,再對TextBox1,TextBox2進行編輯,點擊ENDER還是會直接執行Button1.click的代碼.  
   
想問一下這種情況是因為什麼,要怎麼樣才能解決和避免這種情況.

---出現此情況的原因------------
這是由於WEB表單的特性決定的,Button1是表單的預設提交按鈕,只要是在這個表單內,除多行文字框外的所有控制項上斷行符號,都會激發Button1

。所以會出現這種情況!!!  

 

---解決辦法---------------
在PAGE_LOAD裡加上
Me.txtApplyID.Attributes.Add("onkeydown", "if(event.keyCode==13){document.all." + butQuery.ClientID + ".click();return   false}")
Me.txtCHANGEID.Attributes.Add("onkeydown", "if(event.keyCode==13){document.all." + butQuery.ClientID + ".click();return   false}")

txtApplyID是輸入框,輸入結束按回車,然後執行後面的butQuery按鈕。

 

 

轉載 http://www.cnblogs.com/xy6521/articles/1352474.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.