Programmatically Adding a User Control to ASP.NET

I have a user control that needs to load a child control when a button is clicked. The problem is that it needs to request a control from another class.

So, in the button click event, I call the function to get my control, and add it to the page, for example:

UserControl ctrl = ExampleDataProvider.GetControl(some params...);
myDetailPane.Controls.Add(ctrl);

The GetControl method looks like this:

public static UserControl GetControl(some params...)
        {
            ExampleDetailPane ctrl = new ExampleDetailPane();
            ctrl.Value = "12";
            ctrl.Comment = string.Empty;
            return ctrl;
        }

This does not work because of the page life cycle — the child_Load page of the control is launched and its controls are set to zero.

I seem to know that my approach is wrong and why, but I don’t know how best to fix it! Can anyone help?

+3
4

, Article - , ,

+7

Page_Init. Button_Click .


(CTRL + C/CTRL + V , ):

, , Page_Init, Page_Load.

, , ​​ , . viewstate Load.

http://msdn.microsoft.com/en-us/library/ms178472.aspx.

Init

, , . .

.

Load

OnLoad , , , .

OnLoad .

+2

:

  • , -, . . . : "display: none" , . , OnClick , , div .
  • You can open another window, although obviously it can be blocked by pop-up blockers.
+1
source

If you want to access your control in PostBack or want to bind an event, you must create it in the CreateChildControls () method.

    private UserControl _uc = null;

/// <summary>
    /// Creates all controls.
    /// </summary>
    /// <remarks>All the controls must be created in this method for the event handler</remarks>
    protected override void CreateChildControls()
    {
        _uc = new UserControl ();

        this.Controls.Add(_uc);
        base.CreateChildControls();
    }
+1
source

Source: https://habr.com/ru/post/1728182/


All Articles