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

后端 未结 3 964
野性不改
野性不改 2020-12-16 06:18

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

3条回答
  •  一生所求
    2020-12-16 07:12

    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
    }
    

提交回复
热议问题