473,406 Members | 2,220 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Dynamically Loading a UserControl

Hello,
I have a page with a RadioButtonList and a PlaceHolder control. The
RadioButtonList's AutoPostBack attribute is set to TRUE and its
SelectedIndexChanged event loads one of three UserControls into the
PlaceHolder's child control collection depending upon which of the three
radio buttons is selected. Each of the three UserControls have postback
events themselves triggered by button clicks. The problem I'm having is
keeping track of what UserControl to load upon a page being posted back. My
SelectedIndexChanged event will load a UserControl dynamically just fine,
however, in the event that the dynamically loaded user control itself issues
a postback the parnets Page_Load event must remeber which UserControl to
reload so it can handle its postback. In order to do this, I store the
loaded control's name in the ViewState. This solution causes a problem in
that moveing from one dynamically loaded UserControl to another will cause
two controls to be displayed at the same time. To fix this my
SelectedIndexChanged event will remove the first child control in the
PlaceHolder. However, this solution totally screws with my postback such
that they do not fire porperly. Here is an example of what I'm doing:

private void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ControlName"] != null)

PlaceHolderControl.Controls.Add(LoadControl(ViewSt ate["ControlName"].ToStrin
g()));
}

private void MyRadioButtonList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (PlaceHolderControl.HasControls())
PlaceHolderControl.Controls.RemoveAt(0);

ViewState["ControlName"] = MyRadioButtonList.SelectedValue;

PlaceHolderControl.Controls.Add(LoadControl(MyRadi oButtonList.SelectedValue)
);
}

Any suggestions would be much appreciated.
- Harry
Nov 19 '05 #1
4 3080
I did something similar in an application I wrote... I ended up placing all the controls on the page, hidden, then turned on the appropriate one.

The problem with your approach (which was my inital approach) is that the event code is fired first. So, the dynamic control doesn't exist when a parent event fires.

Here's what I did...
on the aspx page...

<asp:PlaceHolder ID="appArea" Runat="server"></asp:PlaceHolder>
<extn:companyFinder id="ctlCompanyFinder" runat="server" visible="false" />
<extn:company id="ctlCompany" runat="server" visible="false" />
then, in the code behind...
private void Page_Load(object sender, System.EventArgs e)
{

if (this.IsPostBack)
{
if (Session["_extn_control"] != null)
currentControl = this.FindControl(Session["_extn_control"].ToString());

if (currentControl != null)
{
currentControl.Visible = true;
}
}
}

protected void MenuItemHandler(object sender, System.EventArgs e)
{
MenuItem item = (MenuItem)sender;
switch (item.ID)
{
case "mnuFindCompany":
ctlCompanyFinder.Visible = true;
Session["_extn_control"] = "ctlCompanyFinder";
break;
}//end switch item

}//end MenuItemHandler

I used a session variable to trake the name of the current control, but you could certainly use viewstate.

"Harry" <ro******@vu.union.edu> wrote in message news:%2****************@tk2msftngp13.phx.gbl...
Hello,
I have a page with a RadioButtonList and a PlaceHolder control. The
RadioButtonList's AutoPostBack attribute is set to TRUE and its
SelectedIndexChanged event loads one of three UserControls into the
PlaceHolder's child control collection depending upon which of the three
radio buttons is selected. Each of the three UserControls have postback
events themselves triggered by button clicks. The problem I'm having is
keeping track of what UserControl to load upon a page being posted back. My
SelectedIndexChanged event will load a UserControl dynamically just fine,
however, in the event that the dynamically loaded user control itself issues
a postback the parnets Page_Load event must remeber which UserControl to
reload so it can handle its postback. In order to do this, I store the
loaded control's name in the ViewState. This solution causes a problem in
that moveing from one dynamically loaded UserControl to another will cause
two controls to be displayed at the same time. To fix this my
SelectedIndexChanged event will remove the first child control in the
PlaceHolder. However, this solution totally screws with my postback such
that they do not fire porperly. Here is an example of what I'm doing:

private void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ControlName"] != null)

PlaceHolderControl.Controls.Add(LoadControl(ViewSt ate["ControlName"].ToStrin
g()));
}

private void MyRadioButtonList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (PlaceHolderControl.HasControls())
PlaceHolderControl.Controls.RemoveAt(0);

ViewState["ControlName"] = MyRadioButtonList.SelectedValue;

PlaceHolderControl.Controls.Add(LoadControl(MyRadi oButtonList.SelectedValue)
);
}

Any suggestions would be much appreciated.
- Harry

Nov 19 '05 #2
Hello Again,

Quick update, I have added code to my Page_Load event such that it will only
load the control named in the ViewState if the PostBack was NOT raised by
the RadioButtonList. The updated code looks as follows:

if (ViewState["ControlName"] != null &&

Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_0" &&

Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_1" &&

Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_2")

This corrects the problem, however, an exception is thrown when switching
user controls to load by clicking various radio buttons in the list. The
exception reads as follows:

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.

Looks like my updated solution is not acceptable afterall. This is puzling
since the ASP.NET exception indicates the control must be reloaded during
the PostBack, however, I did this the first time around and then removed it
when the SelectedIndexChanged event occured and replaced it with the
requested UserControl, but that solution failed as well since the newly
added UserConrol did not handle PostBacks correctly (see my original code).

- Harry

"Harry" <ro******@vu.union.edu> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hello,
I have a page with a RadioButtonList and a PlaceHolder control. The
RadioButtonList's AutoPostBack attribute is set to TRUE and its
SelectedIndexChanged event loads one of three UserControls into the
PlaceHolder's child control collection depending upon which of the three
radio buttons is selected. Each of the three UserControls have postback
events themselves triggered by button clicks. The problem I'm having is
keeping track of what UserControl to load upon a page being posted back. My SelectedIndexChanged event will load a UserControl dynamically just fine,
however, in the event that the dynamically loaded user control itself issues a postback the parnets Page_Load event must remeber which UserControl to
reload so it can handle its postback. In order to do this, I store the
loaded control's name in the ViewState. This solution causes a problem in
that moveing from one dynamically loaded UserControl to another will cause
two controls to be displayed at the same time. To fix this my
SelectedIndexChanged event will remove the first child control in the
PlaceHolder. However, this solution totally screws with my postback such
that they do not fire porperly. Here is an example of what I'm doing:

private void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ControlName"] != null)

PlaceHolderControl.Controls.Add(LoadControl(ViewSt ate["ControlName"].ToStrin g()));
}

private void MyRadioButtonList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (PlaceHolderControl.HasControls())
PlaceHolderControl.Controls.RemoveAt(0);

ViewState["ControlName"] = MyRadioButtonList.SelectedValue;

PlaceHolderControl.Controls.Add(LoadControl(MyRadi oButtonList.SelectedValue) );
}

Any suggestions would be much appreciated.
- Harry

Nov 19 '05 #3
Jason,
Thank you for the reply. I have tried your approach of putting all the
UserControls on the .aspx page and toggling the Visible attribute on
individual UserControls as needed. The only problem with this method is that
even though a page may not be visible, its Page_Load method is still called
for each UserControl on the page. This may or may not be a performance
problem depending on what initialization is going on in all the Page_Load
events. For instance, in your example, both "companyFinder" and "company"
are being loaded and perhaps populating DataTables with SQL data, however,
only one user control is being rendered. I suppose you could work around
this by using Session keys keep track of which control is to be loaded such
that Page_Load events will skip over their initialization code if the
selected control isn't specified by the Session key/value pair.

In the end I was thinking of having the RadioButtonList's
SelectedIndexChanged event do a Server.Transfer and apend a QueryString to
the URL, such as ...&View="SmallView.ascx" or ...&View="LargeView.ascx" that
identifies which control to load dynamically. In this case all the parent
..aspx page that loads the dynamic user control has to do is look at the
Request["View"] query string to know which control to load.

- Harry
"Jason Penniman" <jp*******@actcci.com> wrote in message
news:Od**************@TK2MSFTNGP11.phx.gbl...
I did something similar in an application I wrote... I ended up placing all
the controls on the page, hidden, then turned on the appropriate one.

The problem with your approach (which was my inital approach) is that the
event code is fired first. So, the dynamic control doesn't exist when a
parent event fires.

Here's what I did...
on the aspx page...

<asp:PlaceHolder ID="appArea" Runat="server"></asp:PlaceHolder>
<extn:companyFinder id="ctlCompanyFinder" runat="server" visible="false" />
<extn:company id="ctlCompany" runat="server" visible="false" />
then, in the code behind...
private void Page_Load(object sender, System.EventArgs e)
{

if (this.IsPostBack)
{
if (Session["_extn_control"] != null)
currentControl =
this.FindControl(Session["_extn_control"].ToString());

if (currentControl != null)
{
currentControl.Visible = true;
}
}
}

protected void MenuItemHandler(object sender, System.EventArgs e)
{
MenuItem item = (MenuItem)sender;
switch (item.ID)
{
case "mnuFindCompany":
ctlCompanyFinder.Visible = true;
Session["_extn_control"] = "ctlCompanyFinder";
break;
}//end switch item

}//end MenuItemHandler

I used a session variable to trake the name of the current control, but you
could certainly use viewstate.

"Harry" <ro******@vu.union.edu> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hello,
I have a page with a RadioButtonList and a PlaceHolder control. The
RadioButtonList's AutoPostBack attribute is set to TRUE and its
SelectedIndexChanged event loads one of three UserControls into the
PlaceHolder's child control collection depending upon which of the three
radio buttons is selected. Each of the three UserControls have postback
events themselves triggered by button clicks. The problem I'm having is
keeping track of what UserControl to load upon a page being posted back. My SelectedIndexChanged event will load a UserControl dynamically just fine,
however, in the event that the dynamically loaded user control itself issues a postback the parnets Page_Load event must remeber which UserControl to
reload so it can handle its postback. In order to do this, I store the
loaded control's name in the ViewState. This solution causes a problem in
that moveing from one dynamically loaded UserControl to another will cause
two controls to be displayed at the same time. To fix this my
SelectedIndexChanged event will remove the first child control in the
PlaceHolder. However, this solution totally screws with my postback such
that they do not fire porperly. Here is an example of what I'm doing:

private void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ControlName"] != null)

PlaceHolderControl.Controls.Add(LoadControl(ViewSt ate["ControlName"].ToStrin g()));
}

private void MyRadioButtonList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (PlaceHolderControl.HasControls())
PlaceHolderControl.Controls.RemoveAt(0);

ViewState["ControlName"] = MyRadioButtonList.SelectedValue;

PlaceHolderControl.Controls.Add(LoadControl(MyRadi oButtonList.SelectedValue) );
}

Any suggestions would be much appreciated.
- Harry

Nov 19 '05 #4
Harry < ro******@vu.union.edu > wrote:
Hello Again,
Quick update, I have added code to my Page_Load event such that it will
only load the control named in the ViewState if the PostBack was NOT
raised by the RadioButtonList. The updated code looks as follows:
if (ViewState["ControlName"] != null &&
Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_0" &&
Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_1" &&
Request["__EVENTTARGET"] != ModeRadioButtonList.ClientID + "_2")
This corrects the problem, however, an exception is thrown when switching
user controls to load by clicking various radio buttons in the list. The
exception reads as follows:
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.
Looks like my updated solution is not acceptable afterall. This is puzling
since the ASP.NET exception indicates the control must be reloaded during
the PostBack, however, I did this the first time around and then removed
it when the SelectedIndexChanged event occured and replaced it with the
requested UserControl, but that solution failed as well since the newly
added UserConrol did not handle PostBacks correctly (see my original
code). - Harry
"Harry" <ro******@vu.union.edu> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hello,
I have a page with a RadioButtonList and a PlaceHolder control. The
RadioButtonList's AutoPostBack attribute is set to TRUE and its
SelectedIndexChanged event loads one of three UserControls into the
PlaceHolder's child control collection depending upon which of the three
radio buttons is selected. Each of the three UserControls have postback
events themselves triggered by button clicks. The problem I'm having is
keeping track of what UserControl to load upon a page being posted back.

My
SelectedIndexChanged event will load a UserControl dynamically just fine,
however, in the event that the dynamically loaded user control itself

issues
a postback the parnets Page_Load event must remeber which UserControl to
reload so it can handle its postback. In order to do this, I store the
loaded control's name in the ViewState. This solution causes a problem in
that moveing from one dynamically loaded UserControl to another will
cause two controls to be displayed at the same time. To fix this my
SelectedIndexChanged event will remove the first child control in the
PlaceHolder. However, this solution totally screws with my postback such
that they do not fire porperly. Here is an example of what I'm doing:
private void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ControlName"] != null)

PlaceHolderControl.Controls.Add(LoadControl(ViewSt ate["ControlName"].ToStr
in
g()));
}
private void MyRadioButtonList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (PlaceHolderControl.HasControls())
PlaceHolderControl.Controls.RemoveAt(0);
ViewState["ControlName"] = MyRadioButtonList.SelectedValue;

PlaceHolderControl.Controls.Add(LoadControl(MyRadi oButtonList.SelectedValu
e)
);

I have the least hassle with dynamic controls when I have references to each
possible Control explicity, then just create a new object for that reference
and add it to the placeholder as needed. For instance:
Control uc1;
Control uc2;

if (someCondition)
{
uc1 = LoadControl("UserControl1");
uc1.ID = "uc1";
placeHolder.Controls.Add(uc1);
}
else
{
//load uc2 in same manner
}
At any rate, if I had to guess I'd say the reason Viewstate is getting
confused has to do with naming conflicts. Unless you explicitly set the ID,
it will usually get something like "_ctl4" or something, where "4" is
however many auto-named controls there have been so far. What might be
happening then is:

1) On first request, you load a UserControl of type "UC1" to the
placeholder, ID is not explicitly set, so it is "_ctl1"
2) You make a postback
3) On this request, you want to switch to a different control, "UC2" so you
load it, it gets same ID "_ctl1" and ViewState goes to try to load - blows
up because it's a different control than "_ctl1" was before

In short, I would try either setting the ID explicity within each user
control you have to something unique or setting it when you create it in the
parent.
Nov 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Mark Stokes | last post by:
Hi guys, I have seen various messages on this front, but none specific to my requirement. I have an application that dynamically loads a user control and displays it on the page during the...
1
by: Sundaresan | last post by:
I've a form where I load two user controls dynamically. User Control-1 has a no.of dropdowns and based on the selection I typically populate a datagrid in the user control-2, Also the I could...
2
by: Eric | last post by:
I'm trying to dynamically load a user control using on the .NET framework (not Visual Studio). The control was designed in Visual Studio and is named: Disable.ascx The first line is: <%@...
1
by: Josh | last post by:
Hi Guys, I have been having a big problem with trying to pass parameters into a user control when the user control is dynamically loaded into a placholder. I am developing in c#. I have get...
5
by: darrel | last post by:
I'm still a bit stumped on how to load a usercontrol, and then pass a property value (or variable value) to it. Here's what I'm using to load the UC: localCUstomControl.ascx.vb...
6
by: Steve Booth | last post by:
I have a web form with a button and a placeholder, the button adds a user control to the placeholder (and removes any existing controls). The user control contains a single button. I have done all...
2
by: A.Wussow | last post by:
Hi Everybody, i want to load dynamically content from some user controls (with forms, or some data-controls) using atlas. So i use an UpdatePanel for loading the user control into a placeholder....
0
by: Jesper Lund Stocholm | last post by:
I have problems with sending javascript to the client from a dynamically loaded usercontrol. I have a single page that dynamically loads controls into a table cell in a HTML-table. For one of...
3
by: | last post by:
Hello all, I have a UserControl that renders some HTML content. I now need to dynamically load and render "n" instances of this usercontrol on a host aspx page inside a panel control based upon...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.