Type casting your User Control Class in ASP .Net 2.0+

Posted on July 31, 2008

I ran into a little bit of a strange issue today:

I created a User Control that was being used multiple times on a page. It contained a few public methods and properties that allowed me to delegate loading and saving of the data to the control.

Since I have a personal aversion to typing out the same thing for controls with different names, I wanted to just loop through the Controls, check for the type, cast, and call the method. Seems simple right?

Not so much.

First I had a bit of trouble getting the actual type to cast. I googled and found a solution:

((ASP.controls_myControlName_ascx) myControl1).LoadMethod();

Super. The code ran just dandy on my local machine.

However, I ran into a bit of trouble when we deployed the code to our testing environment. It couldn’t figure out what ASP.controls_myControlName_ascx. Of course, this happened when my internet was down and I was working at home and everyone was freaking out.

To fix the deployment issue, first, I got rid of the “ASP.” prefix. Then it wouldn’t compile on my local machine. Bah.

In googling, I came across this article: Understanding Page Inheritance in ASP.Net 2.0 by Rick Strahl. I used his solution for Pages and created an abstract base class which inherited from UserControl and contained abstract public methods. I put the abstract class into the App_Code folder and wa-la! I could cast the controls to the base class and call the methods and set public properties. Yay!

Sort of. It’s actually kind of a lame solution but it works and is acceptable.


No Replies to "Type casting your User Control Class in ASP .Net 2.0+"


    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.