Programmatically Adding User Controls Inside An UpdatePanel

后端 未结 3 1184
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 16:05

I\'m having trouble dynamically adding controls inside an update panel with partial postbacks. I\'ve read many articles on dynamic controls and I understand how to add and m

3条回答
  •  隐瞒了意图╮
    2020-12-13 16:24

    I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification:

    1) Use LoadViewstate instead of Page_Load to load the user control:

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
    
        if (!string.IsNullOrEmpty(CurrentUserControl))
            LoadDataTypeEditorControl(CurrentUserControl, panelFVE);
    }
    

    2) Don't forget to set the control id when loading the usercontrol:

    private void LoadDataTypeEditorControl(string userControlName, Control containerControl)
    {
        using (UserControl myControl = (UserControl) LoadControl(userControlName))
        {
            containerControl.Controls.Clear();
    
            string userControlID = userControlName.Split('.')[0];
            myControl.ID = userControlID.Replace("/", "").Replace("~", "");
            containerControl.Controls.Add(myControl);
        }
        this.CurrentUserControl = userControlName;
    }
    

提交回复
热议问题