Jaguar
Jaguar

Reputation: 5958

How to pass a Type to a UserControl

I have a UserControl (lets say Foo.ascx) that has a Type public property with the name Bar. I am looking for a way that when i declare this usercontrol in the source view of the markup part to pass a type. for example

<%@ Register Src="~/Controls/Foo.ascx" TagPrefix="prfx" TagName="fooCtrl" %>

and then use it as

<prfx:fooCtrl ID="theId" runat="server" />

if for example i wanted to pass to the control the type of string (such as typeof(string)) something that would have this effect

<prfx:fooCtrl ID="theId" runat="server" Bar="typeof(string)" />

how can it be done? Before anyone asks, the reason is that i have many other properties in this usercontrol that i pass in this manner and i want to avoid using the CodeBehind just to pass the Type

Upvotes: 2

Views: 1129

Answers (2)

user1228
user1228

Reputation:

Short answer, you can't do this. The editor and compiler treats .ascx files as (in the end) XML. That means on "deserialization" properties can be converted to various primitive types but not complex types such as System.Type. To work, what you would like to do would require, at some point during compilation, that an attribute in an xml document not be treated as text, not converted to a simple type, but interpreted and executed as code. Without altering how Visual Studio and the ASP.NET compiler works, this won't happen.


Workaround:

  1. Create a public property of type string in your UserControl
  2. Pass the AssemblyQualifiedName of the type you wish to pass to the UserControl via this attribute
  3. Use the GetType(string) overload to get an instance of this type within your code.

    <prfx:fooCtrl ID="theId" runat="server" Bar="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

and, in code:

/* ... */
var barType = Type.GetType(this.Bar);
// do whatever you want with this type

Upvotes: 2

Anders Fjeldstad
Anders Fjeldstad

Reputation: 10814

You could add a property of type string to your user control called for example TypeName:

public string TypeName { get; set; } // Validation omitted for brevity

Then change the implementation of your Bar property to:

public Type Bar { get { return Type.GetType(TypeName); } }

That way you could write:

<prfx:fooCtrl ID="theId" runat="server" Bar="System.String" />

Have all code that needs to use the type call the Bar property.

Upvotes: 4

Related Questions