Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you move ASP.Net controls to different places on the Web form at runtime?

Is there an accepted way to "move" a control.

My client wants to place a certain chunk of markup (representing some visual element) in one of several different places on the page. The locations are different to the point that I can't effect the change on CSS along (by floating it or something).

I considered just putting the control in multiple spots with Visible set to "false," then displaying the one in the place they wanted for that particular page.

However, the code for this control is not trivial -- there's a couple template sections, for instance. Having to dupe this in multiple places would get unwieldy. Also, I don't want to have to work with this control strictly from the code-behind for the same reason.

So, I'd like to put it in one place on the Web form, the move it around based on where I want it. Could I put Placeholders in different spots, have the control in one spot, then remove and add it to the right spot? I suspect this would work.

Does someone have a better idea? Is there a best practice for this?

like image 648
Deane Avatar asked Apr 03 '09 14:04

Deane


1 Answers

I'd recommend using a placeholder control, moving your markup into a separate user control, then loading this at runtime and adding it to the relevant placeholder.

Eg.

// Load a user control
MyControl userCtrl = (MyControl) LoadControl("~/Controls/MyControl.ascx");

// Or create an instance of your control
SubclassedControl subclassedCtrl = new SubclassedControl();

// Do stuff with controls here
userCtrl.LoadData();
subclassedCtrl.Text = "Hello World";

// Check which placeholder to add controls to
PlaceHolder placeHolder = (foo=="bar") ? placeHolder1 : placeHolder2;

// Add the controls
placeHolder.Controls.Add(userCtrl);
placeHolder.Controls.Add(subclassedCtrl);

This will avoid cluttering up your page with unnecessary markup, and loading it at runtime will also avoid unnecessary confusion later, when another developer looks at the code and can't immediately see why a control is in one place in the markup, but renders on a completely different part of the page.

like image 125
Mun Avatar answered Sep 29 '22 20:09

Mun