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))
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.