views:

141

answers:

5

Is there a difference in behavior between adding a control to the aspx page directly and loading a control programmatically and adding to a placeholder?

The control inherits from System.Web.UI.WebControls.DataBoundControl.

The reason I ask is that I have a control that works when I add it to the aspx page like so:

...
<blah:GoogleMap ID="GoogleMap1" runat="server" Width="640px" Height="600px" ... DataSourceID="_odsMarkers" DataAddressField="Address" DataTextField="Description">
</blah:GoogleMap>
...

But not when I use the following in a codebehind page:

GoogleMap map = (GoogleMap)this.LoadControl(typeof(GoogleMap), new object[] { });
//... set properties
this.placeholder1.Controls.Add(map); //add to placeholder

Anyone have any quick ideas why this might be the case?

+1  A: 

If you are setting properties outside of the LoadControl call, why are you making that new empty object array instead of just using the overload that has one parameter?

Also, if you attach a debugger to it and step through, do you notice anything weird about the control before you do your Controls.Add() call? Is there an exception being thrown? if so, which one? if not, what does the markup in the browser look like for where the placeholder is?

Matt Briggs
+1  A: 

"Works" is kind of ambiguous, but if you mean, event handlers are never executed, you need to load it in the page onload event.

John MacIntyre
+3  A: 

The control tree ends up the same if you define in markup or add programmatically. However there is plenty of room for the control implementor to screw up along the way.

You can go look how ASP.NET compiles the aspx:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

The timing when the control is added to the page might be an issue. The usual pattern is add the control in an overload of the CreateChildControls method. If the control needs to resolve viewstate you need to make sure this is called during init, e.g. by calling EnsureChildControls.

Adding to ninja's debbugging hint. Does it make any difference if you add a label the same way. Does it show up?

Cristian Libardo
+2  A: 

Is this a user control or server control?

If it's a user control they should be loaded by their path and not their type:

GoogleMap map = (GoogleMap)this.LoadControl("~/Controls/GoogleMap.ascx");

If it's server control then you can just new up an instance:

GoogleMap map = new GoogleMap();

after you have the instance and add it to the control tree (by inserting it into the PlaceHolder) it should perform the same as when it would have been declared in the markup.

Y Low
+1  A: 

If the control requires the use of viewstate you must ensure that it is added to the page BEFORE the Page_Load event, otherwise viewstate will not be populated and most likely events and other items will not function properly.

Mitchel Sellers