Control Add PostBack Problem

无人久伴 提交于 2020-01-16 19:44:48

问题


I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.

So How can I add control ?


回答1:


Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.

See this link...

ASP.NET Add Control on postback

A very trivial example..

public partial class MyPage : Page
{
    TextBox tb;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        tb = new TextBox();
        tb.ID = "testtb";
        Page.Form.Controls.Add(tb);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //tb.Text will have whatever text the user entered upon postback
    }
}



回答2:


Because you must recreate your controls on every postback, see this article




回答3:


You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.

To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.




回答4:


Add controls in runtime and save on postback:

int NumberOfControls = 0;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState["b1"] = 0;
    }
    else
    {
        if ((int)ViewState["b1"] > 0)
        {
            CreateBtn();

        }
    }
}


protected void btn1_Click(object sender, EventArgs e)
{
    NumberOfControls = (int)ViewState["b1"];

    Button b1 = new Button();
   // b1.Attributes.Add("onclick", "x()");
    b1.Text = "test2";

    b1.ID = "b1_" + ++NumberOfControls;
    b1.Click +=new  System.EventHandler(btn11);
    Panel1.Controls.Add(b1);
    ViewState["b1"] = NumberOfControls;
}

protected void CreateBtn()
{
    for (int i = 0; i < (int)ViewState["b1"];i++)
    {
        Button b1 = new Button();
        // b1.Attributes.Add("onclick", "x()");
        b1.Text = "test2";
        b1.ID = "b1_" + i;
        b1.Click += new System.EventHandler(btn11);
        Panel1.Controls.Add(b1);
    }
}

protected void btn11(object sender, System.EventArgs e)
{
    Response.Redirect("AboutUs.aspx");
}


来源:https://stackoverflow.com/questions/2042270/control-add-postback-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!