Tuesday, April 8, 2008

Setting class property value at run time

While making a simple web user control, I thought of having a property that will pick up the controls on a page and then the based on what form/page control developer has assigned to the user control it will populate its property.

While looking to implement this I hit upon TypeConverter class, but somehow couldn't get this done. From a forum where I posted my question, I learnt that this is because my control inherits from UserControl class and not WebControl class and consequently can't implement TypeConverter. Though I'm not satisfied with this, I'm still to find a working solution.

One of the properties exposed by my user control was "PropertyToPopulate". The control on a page can be a textbox, a 3rd party control(Telerik in my case) or anything else, thus this property was required. I knew that I can set the property value through Reflection in .Net but while trying to find a sample code I came across codes which were very detailed and complex but none of my use. Finally, I was able to filter out things and combine it into one to achieve my objective. Below is what I did:

Dim control As New Object
control = CObj(Me.Parent.FindControl(_FromDateControl))
Dim controlType As Type = control.GetType()
Dim properties As System.Reflection.PropertyInfo
properties = controlType.GetProperty(_PropertyToPopulate)
properties.SetValue(control, newDate, Nothing)

The code above simply, finds the control gets it type and then the property that the user wishes to set. The SetValue() method does the trick of setting the value in the property.

And that was it.

No comments: