Accessing a property using a string containing the property name?

D

Don

Is it possible to access the property of an object using a string containing
the name of the property you want to access? Something like:

oCustomer = New Customer
propname = "FirstName"
Console.Write(GetPropertyValue(oCustomer,propname)) <-- returns
oCustomer.FirstName

- Don
 
S

Shiva

Hi,
Check out System.Type.InvokeMember()

Is it possible to access the property of an object using a string containing
the name of the property you want to access? Something like:

oCustomer = New Customer
propname = "FirstName"
Console.Write(GetPropertyValue(oCustomer,propname)) <-- returns
oCustomer.FirstName

- Don
 
J

Jay B. Harlow [MVP - Outlook]

Don,
In addition to System.Type.InvokeMember, I find CallByName to be a handy
wrapper for System.Type.InvokeMember.

http://msdn.microsoft.com/library/d.../en-us/vblr7/html/vafctcallbynamefunction.asp

Dim value As Object = CallByName(oCustomer, "FirstName",
CallType.Get)

Also I've used TypeDescriptor.GetProperties with much success.

Dim properties As System.ComponentModel.PropertyDescriptorCollection
properties =
System.ComponentModel.TypeDescriptor.GetProperties(oCustomer)
Dim value As Object = properties("FirstName").GetValue(oCustomer)

Hope this helps
Jay
 
D

Don

CallByName is, by far, the simplest of the bunch and wholly adequate for my
needs. Thanks to everyone who responded (and so quickly!)

- Don
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top