简体   繁体   English

单击时动态创建的控件消失

[英]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. 最好在页面OnInit事件上创建动态控件。

Read about the page life cycle here . 在此处阅读有关页面生命周期的信息

  • Create a panel 创建一个面板
  • Do not create on page_load 不要在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]);          
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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