Issue with dynamically loading a user control on button click

前端 未结 1 479
旧巷少年郎
旧巷少年郎 2021-01-23 12:06

I have a page in which I am loading a user control dynamically as follows:

Default.aspx:

    

        
1条回答
  •  情歌与酒
    2021-01-23 12:54

    The problem with the second control is that you are loding it only after the click of button 1. But when some other (not button 1 click) postback happens your second control is not loaded.

    One of possible fixes is saving some flag (e.g. in ViewState) that will help you to determine if your second control should be loaded (and load in on page load).

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "UserControl - 1 button clicked!";
    
        var ctrl = LoadControl("~/UserCtrl2.ascx");
        ctrl.ID = "ucUserCtrl2";
        PlaceHolder2.Controls.Add(ctrl);
    
        this.SecondControlLoaded = true; // This flag saves to ViewState that your control was loaded.
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        var ctrl = LoadControl("~/UserCtrl1.ascx");
        ctrl.ID = "ucUserCtrl1";
        PlaceHolder1.Controls.Add(ctrl);
    
        if (this.SecondControlLoaded)
        {
            var ctrl = LoadControl("~/UserCtrl2.ascx");
            ctrl.ID = "ucUserCtrl2";
            PlaceHolder2.Controls.Add(ctrl);
        }
    }
    

    0 讨论(0)
提交回复
热议问题