How to persist a dynamic control (c#)

前端 未结 4 1148
北荒
北荒 2021-01-16 06:15

As per the title, I have created a custom control.

On a certain button click event, this control is instantiated, then added to the page.

It is a dynamic con

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 06:57

    You should recreate dynamic controls on every postback. The best place to do that is method CreateChildControls.

    To add dynamically control after button click set in click handler some flag (persistent flag - so it should be in viewstate or in sessionstate) - it should indicate that on next page creation your control should be added to it. After this you should set ChildControlsCreated = false;
    After this CreateChildControls are executed again and your control is created correctly and is persistent (till you not clear flag).

    So it should be done in this way:

    protected override void CreateChildControls()
    {
            base.CreateChildControls();
        if (ViewState["AddControl"] == true)
            {
             Controls.Add(new MyControl() {Id = "someId" });
            }
    }
    

    And btn handler

    private void OnShowControlClick(object sender, EventArgs e)
    {
             ViewState["AddControl"] = true;
             ChildControlsCreated = false;
    }
    

提交回复
热议问题