Tip of the day: Set properties with reflection

If you use web sites instead of web application projects and load an user control dynamically, it can be hard to set the properties from code behind since you can´t cast the instance.

What to do? WHAAAAT TO DOOOO??? Well, first of all, take a beer and chill. After that you can take a look at reflection, and especially PropertyInfo.SetValue(...).

Magic: 

using System.Reflection;

void DoMagic()
{

UserControl meLiek = LoadControl("tehcontrolz.ascx");
Type meLiekTehTajp = meLiek.GetType();
PropertyInfo prop = meLiekTehTajp.GetProperty(
"waevvah");
prop.SetValue(meLiek,
"lolz0rz", null);
ControlHolder.Controls.Add(meLiek);

}

More info:
http://msdn.microsoft.com/en-us/library/aa330197(VS.71).aspx

7 Comments

  • Ever heard of an interface? ;)

    I like the lolcode sample though ;)

  • ..or you can add a reference to the ascx in your aspx page like so:



    and in your code behind do something like this:

    tehcontrolz meLiek = (tehcontrolz) LoadControl("~/tehcontrolz.ascx");
    uc.waevvah = "lolz0rz";
    ControlHolder.Controls.Add(meLiek);

    Regards,

    Raj

  • Hi Gabor,

    Yes, but if you have a couple of user controls, do you really want to add a new interface for each one of them? I use a lot of user controls while building a new site since I want the page to be as modular as possible to make it easier to maintain the site and debug the different parts.

    Mikael Söderström

  • Hi Raj,

    Yes that´s true - if you use a web application project! AFAIK you can´t cast the user control to the right class if you use a web site, since you don´t compile the page the ordinary way.

    Please correct me if I´m wrong.

    Mikael Söderström

  • If use a property that is required on each of your controls, you should probably use a custom UserControl base class.


  • An interface or a base class is really a better idea than reflection, especially if you have a lot of user controls, as you seem to. Reflection is slower than direct typed access, and makes code harder to read.

  • I don't use interfaces and *never* had casting problems. The only time I had casting problems is when I didn't use the correct ascx string identifier.

Comments have been disabled for this content.