第三章 為控制項添加事件
好了,我們之前以前開發一個控制項。而且也添加了屬性,開發也很規範,但是那個控制項還差最後一點:添加事件。
系列文章連結:
ASP.NET自訂控制項組件開發 第一章 待續
ASP.NET自訂控制項組件開發 第一章 第二篇 接著待續
ASP.NET自訂控制項組件開發 第一章 第三篇
ASP.NET自訂控制項組件開發 第二章 繼承WebControl的自訂控制項
ASP.NET自訂控制項組件開發 第三章 為控制項添加事件 前篇
ASP.NET自訂控制項組件開發 第三章 為控制項添加事件 後篇
ASP.NET自訂控制項組件開發 第四章 群組控制項開發CompositeControl
ASP.NET自訂控制項組件開發 第四章 群組控制項開發CompositeControl 後篇 --事件冒泡
ASP.NET自訂控制項組件開發 第五章 模板控制項開發
ASP.NET2.0自訂控制項組件開發 第六章 深入講解控制項的屬性
ASP.NET2.0組件控制項開發視頻 初體驗
ASP.NET的開發都是事件驅動的,現在我們就來為控制項添加事件。在說事件之前,希望大家對C#的文法要熟悉,對委託
很事件要懂。
其實定義事件的步驟很簡單:
1.聲明一個委託。
2.定義一個攜帶事件資訊的類。
3.定義事件
4.定義一個通事件發生後,通知其他對象的方法
首先來理清一下我們的思路:
1.在下拉框中選中一個值,並且在輸入框中也輸入相應的值。
2.我們在頁面點擊“提交”按鈕,按鈕就觸發我們自訂的一個事件Validate(驗證輸入資訊的正確行)。
我們在提交的時候要把控制項的資訊傳給伺服器,所以我們要定義一個事件資訊類,來攜帶事件發生時,把個資訊類送
到伺服器。
事件定義如下:
1.定義一個攜帶事件資訊的類。
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace CreditCardForm
6 {
7 public class ValidateCreditCardFormEventArgs:EventArgs
8 {
9 private string paymentMethod;
10 public string PaymentMethod
11 {
12 get
13 {
14 return this.paymentMethod;
15 }
16 }
17
18
19 private string creditCardNo;
20 public string CreditCardNo
21 {
22 get
23 {
24 return this.creditCardNo;
25 }
26 }
27
28
29 private string cardholderName;
30 public string CardholderName
31 {
32 get
33 {
34 return this.cardholderName;
35 }
36 }
37
38 private DateTime expirationDate;
39 public DateTime ExpirationDate
40 {
41 get
42 {
43 return this.expirationDate;
44 }
45 }
46
47
48 public ValidateCreditCardFormEventArgs(string paymentmenthod, string creditcardno,
49 string cardholdername, DateTime expirationdate)
50 {
51 this.paymentMethod = paymentmenthod;
52 this.creditCardNo = creditcardno;
53 this.cardholderName = cardholdername;
54 this.expirationDate = expirationdate;
55 }
56 }
57 }
58
2.聲明一個委託。
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace CreditCardForm
6 {
7 public delegate void ValidateCreditCardFormEventHandler(object sender,ValidateCreditCardFormEventArgs args);
8 }
9
3.定義事件
Code
1 public event ValidateCreditCardFormEventHandler ValidateCreditCardForm;
4.通事件發生後,通知其他對象的方法
Code
1
2 //這個方法是受保護的虛方法
3 protected void OnValidateCreditCardForm(ValidateCreditCardFormEventArgs args)
4 {
5 if (ValidateCreditCardForm != null)
6 handler(this, args);
7 }
這樣幾個步驟之後,控制項的事件就寫完了。大家試試! 有問題,我們下篇接著說!
今天寫到這裡,希望大家反饋資訊,聽聽大家的想法!