简体   繁体   中英

dynamically created controls disappears when click

the dynamic controls went missing right after i click it, why is this happening, and how do i fix it.

protected void Page_Load(object sender, EventArgs e)
{
    /*DropDownList1_SelectedIndexChanged(sender, e);
    Label1.Text += "<br/>huh?";
    Label1.Text = MapPath("dawd");*/
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //PlaceHolder1.Controls.Clear();
    for (int i = 0; i < DropDownList1.SelectedIndex + 1; i++)
    {
        CheckBox cb = new CheckBox();
        cb.AutoPostBack = true;
        cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
        PlaceHolder1.Controls.Add(cb);
        PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
    }
}

void cb_CheckedChanged(object sender, EventArgs e)
{
    //DropDownList1_SelectedIndexChanged(sender, e);
    Label1.Text += "<br/>adsd";
    //throw new NotImplementedException();
}

cheers, Jaf

Dynamically created controls have to be recreated in every postback, or they will not be available and non of their events will fire.

You are only ever adding the checkboxes when the dropdownlist changes, so any other postback will not add them.

It is best to create your dynamic controls on the page OnInit event.

Read about the page life cycle here .

  • Create a panel
  • Do not create on page_load

Add this code

protected override void CreateChildControls()
{
    base.CreateChildControls();
    loadCheckbox();
}

public void loadCheckbox()
{
    int checkCount = 10;
    CheckBox[] chk = new CheckBox[checkCount];

    for(int i == 0; i<=10; i++)
    {
        chk[i] = new CheckBox();
        chk[i].ID = rCmt.cmtkey;
        chk[i].Text = rCmt.rootcommitteename;
        Panel1.Controls.Add(chk[i]);          
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM