Add an event delegate to an ASP.NET user control event handler

I have web user control in an asp.net keyboard. It has buttons for all digits, a text box for displaying the input and cleaning and send buttons. The user control is located in the AJAX update panel, so it can be easily shown / hidden. (The application is intended for tablet browsers). I need to add a delegate to the subMitButton ClickEventHandler inside my user control inside the AJAX update panel. Any suggestions? Is it possible? I do not want to use a soft numeric keypad on the tablet, because this is the way to the big. I could share my user control and use its code inside my website, but I would prefer to use user control as intended.

+4
source share
2 answers

you can raise an event from usercontrol that you can handle on the page.

You can declare an event.

public event EventHandler SubmitButtonClick;
 protected void OnSubmitButtonClick()
{
    if (SubmitButtonClick!= null)
    {
        SubmitButtonClick(this, new EventArgs());
    }
}

And then on the page handle the event.

  WebUserControl1.SubmitButtonClick+= 
    new WebUserControl.EventHandler(WebUserControl1_SubmitButtonClick);
 private void WebUserControl1_SubmitButtonClick(object sender, EventArgs e)
{
    Label1.Text = "Button Pressed";
}
+8
source

Due to the life cycle of an ASP.NET web page, I get Nulls when I set public properties in a user control from the main page. These variables go beyond the scope after the page is sent to the client. However, this is a simple solution that will allow you to be notified when an event occurs in your user control.

NOTE. There are some problems with Page.Context when they return to the main page, so changing the actions that affect the presentation may not work.

...

 // UC - setting up delegate and usercontrol property to store it
 public delegate void CallbackAction(object sender, CustomEventArgs e);
 public CallbackAction OnCallbackAction
 {
    get { return Session["CallbackAction"] as CallbackAction;  }
    set { Session["CallbackAction"] = value; }

 }

- UserControl ,

// UC - callback from within the usercontrol
protected void UserControlButton_Click(object sender, EventArgs e)
{
   if (IsPostback)
   {
      // do some processing
      if (this.OnCallbackAction != null)
      {
         this.OnCallbackAction.Invoke(this, new CustomEventArgs("ET phone home") );
      }
   }

}

, usercontrol. usercontrol

// Main Page - load event 
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostback)
   {
      // register with usercontrol
      this.UserControlFoo.OnCallbackAction += CallbackFromUserControl_Click;
   }
}

// Main Page - this event will get called back when ET phones home
protected void CallbackFromUserControl_Click(object sender, CustomEventArgs e)
{
   // phoned home from usercontrol
}
+1

Source: https://habr.com/ru/post/1528849/


All Articles