[ .NET ] Calling a page method in the UserControl Event

- quarta-feira, 3 de março de 2010

Today i had a problem with a usercontrol issue. I have "CreateCategory.ascx" inside a "RegisterPage.aspx"page, I need that when CreateCategory submit button get fired, RegisterPage reloads the category Dropdownlist.

to resolve this issue i created a SetHandler method inside the UserControl, this method just receive an EventHandler and insert it on submit button click event.

public void SetHandler(EventHandler eh)

{

     btnSubmit.Click += eh;

}

 

in the RegisterPage OnInit event i call SetHandler method passing a EventHandler

 

protected void AnEvent(object sender, EventArgs e)

{

    /// DO SOMETHING

}

 

protected override void OnInit(EventArgs e)

{

    base.OnInit(e);

    CreateCategoryUserControl.SetHandler(AnEvent);

}

just it resolved my problem. Attention on OnInit method, if u do it on Page_Load on post back it will loose the event handled.



Blogado por Rafa Almeida as 17:51

Rafael Almeida

-

5/3/2010 - 8:18


Attrakt by the observation, it can be done, but in the same way u have to set the handler in the init event.

Attrakt

-

3/3/2010 - 22:31


That's a really weird way of handling that problem. Instead, you should have your UserControl expose an event of its own, like this: public event EventHandler SubmitButtonClicked; Then add an event handler for the Click event on the Submit button in your UserControl: protected void btnSubmit_OnClick(object sender, EventArgs e) { if (SubmitButtonClicked != null) { SubmitButtonClicked(this, e); } } Then you can add an event handler for the SubmitButtonClicked event at Page level. Standard observer pattern implementation.
Rafael Almeida Rafael da Silva Almeida, 22 Desenvolvedor;
C#, VB.NET, Java, C, Phyton, Linq, MVC;
VSTS, SQL, TV Digital, Xletview;
eusou@rafaelalmeida.net
SKYPE: stupied4ever
MSN: r.almeidasilva@terra.com.br
Twitter

Ultimos Posts

Amigos