Dave Burke - Freelance .NET Developer specializing in Online Communities

A freelance .NET Developer

System.Reflection SetProperty

This is my second post on using reflection.  Here is the first.  I started rewriting a web app which lists items then on selection shows the item summary (along with several item-specific functions) to support other similar item types.  So it was an opportunity to implement a base class in the solution's WebUI project namespace and go from there.  A method I wanted to use in the base class set a property in a control in the web project's .ASPX page.  I've used reflection to get a property in a remote class web control, but never set a property.  Here's how it works for me.

System.Web.UI.Control uc_doclist = Page.FindControl("uc_doclist");
Type ucType = uc_doclist.GetType();
System.Reflection.PropertyInfo prop = ucType.GetProperty("pid");
ucType.InvokeMember ("pid", BindingFlags.Default | BindingFlags.SetProperty,null,
     uc_doclist, new object [] {int.Parse(e.CommandArgument.ToString())});


In my googling I found two reflection sources which were helpful:

 

Comments

Fabrice said:

You could also simply cast you control to a base class which has the property you want to access instead of using reflection.
# November 14, 2003 6:12 AM

Dave Burke said:

That's an excellent point, Fabrice. Thanks. But if I understand correctly, the base class which had the control and its property was the web page, and in this case multiple web pages will use the remote base class which I will only know at runtime (yeah, some duplication at the UI level for simplification, though I should redesign further.) You're right though, the cast to the base web page is definitely cleaner.

# November 14, 2003 9:06 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)