VB.NET String Property Access to a Class Property

I have a function that updates a client in a database. The client object is passed along with a string array of fields / properties that need to be updated. I need a way to access each property in a client object based on what is in the array. Basically, I'm looking for the VB.NET equivalent for this javascript:

var fields = ["Firstname","Lastname","DOB"]; for(field in fields) { var thisField = fields[field]; client[thisField] = obj[thisField]; } 

Any help would be greatly appreciated! Thanks Stack.

+4
source share
1 answer

You can use Reflection for this. Without knowing more about how your data objects are configured, I cannot give you a great example, but here's a general idea:

 Dim myPerson As New Person myPerson.FirstName = "John" myPerson.LastName = "Doe" myPerson.DOB = #1/1/2000# Dim myUpdates As New Dictionary(Of String, Object) myUpdates.Add("FirstName", "Adam") myUpdates.Add("LastName" , "Maras") myUpdates.Add("DOB" , #1/1/1990#) Dim personType As Type = GetType(Person) For Each kvp As KeyValuePair(Of String, Object) In myUpdates Dim propInfo As PropertyInfo = personType.GetProperty(kvp.Key) If propInfo IsNot Nothing Then propInfo.SetValue(myPerson, kvp.Value) End If Next 
+5
source

All Articles