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

后端 未结 3 970
野性不改
野性不改 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:06

    Default.aspx

    
    
    

    Default.aspx.cs

     protected void Page_Load(object sender, EventArgs e)
     {
         var ctl = LoadControl("Controls/UserControl.ascx");
         ph1.Controls.Add(ctl);
    }
    

    UserControl.ascx

    User control

    UserControl.ascx.cs

    protected void btn1_Click(object s, EventArgs e)
    {
        Response.Write("You clicked me, yay");
    }
    

    All works like a charm. I see the "You clicked me, yay" written when I click the button

    Point of attention. If you try to load the controls dynamically in your example in the handler for SelectedItemChanged event of the dropdown control, it will fail, because of the way that lifecycle works for ASP.Net page. Instead you should handle such control creation in the PageLoad event of the page, like this example below Default.aspx

    
        
        
        
    
    
       
    

    Default.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            switch (ddl1.SelectedValue)
            {
                case "1":
                    var ctl = LoadControl("Controls/UserControl.ascx");
                    ph1.Controls.Add(ctl);
                    break;
                case "2":
                    ctl = LoadControl("Controls/UserControl2.ascx");
                    ph1.Controls.Add(ctl);
                    break;
            } 
        }
    }
    

提交回复
热议问题