I have a function that updates a Client in the database. A client object is passed in, along with a string array of fields/properties that should be updated. I need a way of accessing each property in the client object, based on what is in the array. Basically, I am looking for the VB .NET equivalent to this javascript:
var fields = ["Firstname","Lastname","DOB"];
for(field in fields)
{
var thisField = fields[field];
client[thisField] = obj[thisField];
}
Any help will be greatly appreciated! Thanks Stack.
You can use Reflection to do this. Without knowing more about how your data objects are set up, I can't give you a perfect example, but here's the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With