UserControl Events Handled by Page - Thea Burger's Blog

Thea Burger's Blog

Wouldn't you like to know...

News

Photo's!!!

About me

I'm Reading: General Blogs

I'm Reading: Technical Blogs

UserControl Events Handled by Page

Maybe you'll need it someday, maybe you've done it, maybe not :) But I needed to raise an event from a usercontrol, which had to be handled in the containing page. Why? Because I created a RowFilter for a DataView in the usercontrol, and this DataView needs to be bound to a DataGrid on the page. There may be other/better ways, but this worked for me:

The code in the usercontrol:
//Declare custom public event handler
public event EventHandler Bind;

private void btnFilter_Click(object sender, System.EventArgs e)
{
      //...create dataview and rowfilter

      //raise custom event
      Bind(this, e);
}

The code in the containing page:
private
void Page_Load(object sender, System.EventArgs e)
{
     //...Load usercontrol (filter1)

//Specify EventHandler in Page to handle Event raised in usercontrol
filter1.Bind +=new EventHandler(filter1_Bind);      
}

private void filter1_Bind(object sender, EventArgs e)
{
      //Respond to event raised  (Bind dataview to datagrid)
}

Comments

Eduard Penzhorn said:

remember that you can add as many eventhandlers as you want in this way (on the same event), and (of course) all of them will get fired. That's whats nice about delegate, they can be any method in any class.
# July 16, 2004 3:53 PM

Eddie Kisinger said:

Beautiful, very simplistic and exactly what I was looking for. Your a life saver! Thanks
# May 6, 2005 6:21 PM

jaln said:

handle page
# May 20, 2005 11:17 AM

Lin said:

i have a little question..
I have a text box (HtmlInputText) that i want my User Control to fire the event when the the text is changing.
So.. should i do it in the same way just to add:
txt.Attributes.Add("OnServerChange",OnServerChange(this, new EventArgs()));
?!

I don't know why it doesn't work for me.. :(

thanks - Lin
# May 24, 2005 1:30 PM

Bruce McLeod said:

If you change the access to public as ICECODER suggests, it works like a treat. Until the GUI designer changes it back to protected if you modify the control.
# June 7, 2005 3:53 AM

Dharmesh Solanki said:

good article, but i have a one problem when i raise the customevent like Bind(this, e) in my usercontrol's event(selectchange) then it gives me object reference not set error. PL. reply how to solve that I writing everything as u described into the article Thanks a lot.
# October 18, 2006 12:35 PM