We help IT Professionals succeed at work.

Setting a property from a string value

338 Views
Last Modified: 2013-11-26
Hi

I have a class names Customer with several properties. I have the property I wish to set in one string and the value to set it to in another.

       Dim cust As New Customer
        Dim strProp As String = "name"
        Dim strVal As String = "Chris"

Is there a simple way of setting the property in strProp the the value in strVal?

I've written a function to do it using TypeDescriptor.GetProperties(obj) to get the properties, then finding the one I want and setting it that way but I can't believe this is the quickest way.

Thanks

Chris
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
Unless you want to rewrite your Class to use a different method of storing your properties, this IS the easiest way to do it, based on the strings.

If you wanted to do it differently, you could consider using a hashtable in your class to store values, and use the property name string as your key for the hashtable.

That way, you could say

Obj.HashTable.Item("Key") = "Value"

Otherwise, you're doing it the right way.

Jake

Commented:
Oh Bob,

You always have a much better way of doing things...  Didn't know about that one!

Jake

P.S.  Will that cut down on time?  I.e., his algorithm probably loops through all properties till it finds the right one, whereas .net finds the relevant property for you in your example?
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
Reflection is not the most efficient operation type, but this one should be OK, as it is not too heavy.

Bob

Commented:
Thanks for the info, Bob.

You constantly amaze me with your knowledge of Reflection :)

Jake

Author

Commented:
Cheers guys.

This was related to https://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22774145.html

Thanks for the help with Reflection and I'll issue points but I still can't get it working for .NET1.1 with custom classes as in the link. All very strange. Works fine with 2.0.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.