How to fix problems with the placeholder control and custom web user controls - Digital Tool Factory blog How to fix problems with the placeholder control and custom web user controls - Digital Tool Factory blog

How to fix problems with the placeholder control and custom web user controls

The Problem: You are using an asp.net PlaceHolder control and populating it with a collection of custom web controls.  You then get “Null Reference Exception” and “Are you missing an assembly?” errors.  Your code looks much like this

foreach (string str in strStringList)
{
CustomWebBox cb=new CustomWebBox()[
cb.CustomTitle=str;
myPlaceHolder.Controls.Add(cb);
}

The Cause: The same ID’s are being used over and over agian in the page as the web control repeats.

The Solution: Instead of simply reinitializing the control the “new” keyword, load it manually using Page.LoadControl.  That keeps the id tags different and the error is avoided.  Your code would look something like this.

foreach (string str in strStringList)
{
CustomWebBox cb=(CustomWebBox)Page.LoadControl("~/CustomWebBox.ascx");
cb.CustomTitle=str;
myPlaceHolder.Controls.Add(cb);
}

That’s it!

 

This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog

 

Written By Steve French

 

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.