Specify a class property name with a string variable in vb.net

Good morning all. Well watching "The Shield" last night was not real fulfilling. Like Vic was really going to take Shane down in a parking lot of a hospital. Then there was Dutch doing his best from being seduced by a woman old enough to be his mother. For once, I admired Billings better than Dutch for his willingness to do something about the threat to his family. The good news is next week’s episode looks more promising.

You might be wondering what is up with yesterday’s posting. Well my plan is to take each namespace shown there and its classes therein and explore them in separate blog postings. Its a big undertaking but it will put some rhyme and reason to the things I post.

Of course today is not the day that will start due to a development in a project I am working on. 🙂

I was in a situation where I had an instance of a class called "employee". The properties of employee also happen to be the same as the database table called employee. I had one variable representing the table name and one representing the column name. The original plan was to loop through the columns of the table till I found a match with my employee class property and write the value once I found the right property. The problem was that every time a loop occurred a new database call was needing to be made which made the end result occur quite slowly. (I did not design the employee class. Actually the way they did it was really cool but how were they to know they were going to find themselves in this situation at the time?) So I had to find a way to make my column variable and the employee class properties be able to interact.

So here is how I did it.

First I changed the column variable to object type instead of string. One line of code then observations.

employee.GetType.GetProperty(columnname).GetValue(employee, Nothing)

1. The GetType(Employee) returns an instance of Type that represent the class "Employee".
2. GetProperty(columnname) on the Type object returned from step 1 gives me the PropertyInfo that represent the shared property Instance of type Employee.
3. GetValue() on the returned PropertyInfo from step 2 returns me the value of Employee.(columnname – what that propertys name is).

Anyway, make it a great day!

 

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: