Loading a control from another control


Mike Collins

I have a web app that when I click a menu, I load a control. On one of these
controls, I have a button that when clicked, I need to unload the control to
unload itself and load a different control in its place. I am not sure how to
do this from within a control itself. Can anyone offer any help and show me
what I am doing wrong with my code below?

//This is on one of my controls.
protected void btnSubmit_Click(object sender, EventArgs e)
Control ctl = new Control();
ctl = LoadControl(@"~\UserControls\Marketing\ManageCampaigns.ascx");
ctl.ID = "campaignWizard";
ctl.EnableViewState = true;
Control parent = new Control();
parent = this.Parent.FindControl("PlaceHolder1");



Cowboy \(Gregory A. Beamer\)

Raise an event in the control and have the page handle loading the other
control. If you do what you are attempting to do, you will end up muddling
the waters.

While ASP.NET allows you to circumvent the page when dealing with controls,
you should not do it in all but very simple examples. It locks you into a
major refactor if you ever decide to go to server controls (compiled
controls), as the server control will interact only through events. That may
not seem like a big deal, but the first time you find a control that can be
used in two websites, you will be glad you heeded it, as it is hard to get
rid of code smells with user controls.

It is much better to treat a user control like a server control and have
anything outside its sphere of control done by the page. Taken to the nth,
which is not a bad idea in many implementations, this means you are feeding
the control through properties (from the page) and throwing events with
button clicks, etc. I would at least do the later with nearly every control,
esp. if you have more than one user control on a single page.

There is one downside to this method. You have to wire up the event
delegates, but this is a small price to pay to avoid kludging up your
website by trying to make the control the controller of the page.

Gregory A. Beamer

Subscribe to my blog

or just read it:

| Think outside the box! |



bruce barker

as controls can not play with their parent collections, you need a server
control (probably based on the placeholder) that handles this logic. events
are probably a good way for the children to inform the parent.

-- bruce (sqlwork.com)

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