Reflection and Data Output, Part 1

Reflection is extremely beneficial for outputting data dynamically. Often, we need to be able to change column order or even what displays quickly. Reflection gives us the mechanism to perform late-binding on columns that will be output.

Let's consider an example. Suppose you want to output a table with a few columns--a user's name, country, and ID. My data access layer is going to provide me a list of objects with properties of the same names. I can hardcode my output process to use these names. But what if I expect them to change a lot? Or what if users are going to be able change them themselves? Hardcoding is not an option.

Reflection allows us to solve this problem by reading configuration information and outputting our data columns based on this data.

You will need to add the following declaration:


Private pInfo() As System.Reflection.PropertyInfo
Private PropertyIndexes() As Integer


Then populate this array:


Dim t As Type = MyObjectCollection(0).GetType
pInfo = t.GetProperties


Then set the indexes of the fields to display:


ReDim PropertyIndexes(TotalColumns - 1)
' loop through your array of property names to display
PropertyIndexes(i) = FindPropertyName(PropertyNameToDisplay(i))
' next


Finally, for each of your objects, you will loop through the list of fields to display, using this code to pull the correct fields out of the data access object:


Dim output As Object
output = pInfo(PropertyIndexes(i)).GetValue(MyObjectCollection, Nothing)


Yes, I am throwing a lot at you, and this may not make sense right now. If you are an expert with reflection, you probably see exactly what I am doing. If not, I will dive more deeply in the details next time.

0 comments:

Post a Comment