C# – Button click event not firing within use control in ASP .Net

asp.netc

I am developing an asp web page in which I have a drop down combobox and a place holder below that. When the user selects an item from the drop down combobox, a postback is done to the server side and server loads an asp user control to the place holder in this parent page. Everything upto now is working fine.

In the user control I have a button and the user control code behind is implemented to handle the button click event. The problem is, when I click this button, I can see that the postback is send to the server side (i.e. parent page Page_Load() is invoked in debug mode), but both the user control's Page_Load() or button click event handler is not invoked.

Please help..

Some additional information,

  1. My parent page is not an asp master page. Just a simple asp page.
  2. I am using VS2008 and .Net 3.5 SP1 and C#.

Best Answer

You need to ensure that you UserControl exists so the button click event is triggered when viewstate is rebuilt.

Loading your UserControl in the Page_Load will work the first time. When you click the button and the post_back occurs, Page_Load has not occurred yet. This means the UserControl will not exist, which mean the button does not exist for the event to be wired back up. So the UserControl with the button in it cannot be connected to the click event and the click event wont fire.

Recommend that your user control is loaded in this event.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    //-- Create your controls here
}

Try a sandbox test. In page_load, dynamically create a button with a click event in the Page_Load. You will see that the click event does not fire. Now move the button to the OnLoad event. The click event will fire. Also note, the click event will occur before the Page_Load event. Further proof that the button does not exist at the right time.

Another idea...

You are reloading the usercontrol on the page before the button event occurs. Ensure your LoadControl method is inside the If block

if (!IsPostBack)
{
    //load usercontrol
}
Related Topic