PlaceHolder and UserControls with Events

S

seigo

Hello,

I faced with the following problem. I have a PlaceHolder on a page and
a few UserControls which have custom events, for instance:

public delegate void SelectHandler(object sender, SelectEventArgs
e);
public event SelectHandler OnSelect;

protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
SelectEventArgs ev = new
SelectEventArgs(DropDownList1.SelectedValue);
if (OnSelect != null)
{
OnSelect(this, ev);
}
}

This control fire an event when user select some value from DropDown
and click on Button.

On page where I placed PlaceHolder I need to dynamically load those
UserControls. I use the following code:

protected void Button1_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Clear();
UserControls_WebUserControl control =
(UserControls_WebUserControl)LoadControl("~/UserControls/WebUserControl.ascx");
control.OnSelect += new
UserControls_WebUserControl.SelectHandler(control_OnSelect);
PlaceHolder1.Controls.Add(control);
PlaceHolder1.DataBind();
}

protected void Button2_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Clear();

PlaceHolder1.Controls.Add(LoadControl("~/UserControls/WebUserControl2.ascx"));
PlaceHolder1.DataBind();
}

But I got the exception when trying to load a new UserControl at second
time:

Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial request.

And if I load at first UserControl where I use custom event it doesn't
work.

I decided to place loading UserControl with custom event in overridden
OnInit method:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
PlaceHolder1.Controls.Clear();
UserControls_WebUserControl control =
(UserControls_WebUserControl)LoadControl("~/UserControls/WebUserControl.ascx");
control.OnSelect += new
UserControls_WebUserControl.SelectHandler(control_OnSelect);
PlaceHolder1.Controls.Add(control);
PlaceHolder1.DataBind();
}

but know I cannot load other UserControl to PlaceHolder.

Hope the problem is clear and thanks for any ideas or help!

Regards,
Alex.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top