views:

35

answers:

1

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

+5  A: 

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.

Oded
yea but i want it to be created only when choose from dropdown list, how
@jbs135 - Just as you did. But don't be surprised if a later button/link click means that they disappear (as they don't get recreated).
Oded