2010年11月16日星期二

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 <body>:


<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.

没有评论:

发表评论