how to fire a click_button event from nested ascx before page_load of the aspx on postback?

1k views Asked by At

i have an aspx with usercontrol1 and inside usercontrol1 is usercontrol2. in usercontrol2 i have a button, which what i want to happen is when this button is click, on postback i want to fire first the button_click event before going to page_load event of the aspx. is this possible? i need to fire the button_click event first because on postback in page_load event of aspx, i will redirect the user to another page. So before redirecting the user, i need to get the data entered by the user in usercontrol2. i have read alot about raising an event and delegates but for a newbie like me, i cannot understand it well. please help me on how i can go about this.

UPDATES: I was able to fire the button_click event before the validation of user in aspx page by using addhandler and raise event but the problem is i'm getting NOTHING value. Im thinking of using the postdata (since this happens at postback) but i do not know how and if it is correct way? Please help, below are the codes

In ASPX:

Public Event ShoppingCartClick As EventHandler
Private userControl As userControl2

Protected Overrides Sub OnInit(e As EventArgs)
    AddHandler ShoppingCartClick, AddressOf userControl2.btnShoppingCart_Click
    MyBase.OnInit(e)
End Sub

If IsPostBack Then
   RaiseEvent ShoppingCartClick(sender, e)
   If MyBase.CurrentWebUser.IsLoggedIn Then
      Response.Redirect("ShoppingCart.aspx")
   Else
      Response.Redirect("Login.aspx")
   End If
End If
2

There are 2 answers

0
Gridly On BEST ANSWER

Added as an answer from the comments.

Instead of trying to change normal page lifecycle so the button click is handled before the Page Load, move the logic from the Page Load to a later event so the button click is handled first.

The OnPageLoaded happens after the init, load and event handler events and before the rendering events. This could be a good spot.

A good launching point for page lifecycle information.

1
Sev On

On the click event of the Button I am calling the Parent Page method we discussed above using Reflection and passing the value of the textbox to the method and then the method is invoked and the message is displayed on the screen.

In child user control:

protected void btnSend_Click(object sender, EventArgs e)
{
this.Page.GetType().InvokeMember("DisplayMessage", System.Reflection.BindingFlags.InvokeMethod,     null, this.Page, new object[] { txtMessage.Text });
}

In Parent page you have a DisplayMessage method:

public void DisplayMessage(string textToDisplay)
{
    //DOWORK
}

If you just need to set something then you can just do this. e.g. you need to access a textbox on Parent

TextBox txt= this.Parent.FindControl("txtVisitorName") as TextBox;