Handle UserControl raised event

What is the need?

The scenario is I have a user control which contains a set of textboxes. When the text of a textbox is changed, I want handle this event in the page which contains the user control.

How to do this?

This could be done in 4 steps. 2 in the user control page(.ascx) and 2 in the main page(.aspx).
Step 1: In the .ascs.cs file, declare an EventHandler which will be pasted to the main page after the event in the user control raised.
public event EventHandler TextboxTextChanged;

Step 2: In the function which handles the raised event, in this case is a TextChanged event of a textbox. Assume we have a textbox “tb1” in the UserControl and we handle its TextChanged event in the function”tb1_TextChanged” (Note. AutoPostBack must be set to true):


<asp:TextBox ID="tb1" runat="server" ontextchanged="tb1_TextChanged" AutoPostBack="true"/>

All we need to do is pass the arguments in the TextChanged event to our TextboxTextChanged eventhandler and raise it:


protected void tb1_TextChanged(object sender, EventArgs e)
{
TextboxTextChanged(sender, e);
}

Step 3: Assume we have this UserCtrol in our page, to do so, you can just drag the .ascx page to the design view. You should have the similar two lines in the .aspx page:


<%@ Register src="Textboxes.ascx" tagname="Textboxes" tagprefix="uc2" %>

Another is in the :


<uc2:Textboxes ID="ucTextboxes" runat="server" />

We need manually register the EventHandler we defined in the .axcx in the Page_Load function:


protected void Page_Load(object sender, EventArgs e)
{
// register the event handler for the control
ucTextboxes.TextboxTextChanged += new EventHandler(ucTextboxes_TextboxTextChanged);
}


VS 2010 should be able to help you finish the register after you typed “+=” (press Tab twice, the IS should show the hit).

Step 4: In the step, we create a function to handle the event we registered in the Page_Load:


void ucTextboxes_TextboxTextChanged(object sender, EventArgs e)
{
Label1.Text = ((TextBox)sender).Text;
}

Alternatively, you don’t have to manually register the Event like you do in Step 3 but register it like when you do so for a ordinary server control:


<uc2:Textboxes ID="ucTextboxes" runat="server"
OnTextboxTextChanged="ucTextboxes_TextboxTextChanged" />

In this case, the function must declare as “protected” in Step 4 (There is no “protected” in origin step 4).


Conclusion


The 4 steps are very clear and easy to remember. They are: declare EventHandler, raise event, register event and handle event.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值