Reputation: 63
I am using this code snippet in vb.net . The propertyinfo p is coming out as nothing even though my column name of dataTable is matching with class name attributes
Public Class ReflectionMethods(Of T As New)
' function that set the given object from the given data row
Public Shared Sub SetItemFromRow(item As T, row As DataRow)
' go through each column
For Each c As DataColumn In row.Table.Columns
' find the property for the column. at this point i am getting p as nothing
Dim p As PropertyInfo = item.GetType().GetProperty(c.ColumnName)
' if exists, set the value
If p IsNot Nothing AndAlso row(c) IsNot DBNull.Value Then
p.SetValue(item, row(c), Nothing)
End If
Next
End Sub
End Class
Final end result that I am getting is a class object with everything set to nothing as it is not passing the if condition.
Hi Jon, I have pasted my class snippet down
Public Class StockProduct
Public SupplierName As String
Public ModelName As String
Public ModelDescription As String
Public ProductCategoryName As String
Public ManufacturerName As String
End Class
and I have a dataTable with column match
. Please note the productcategoryName is matched but not seen in screenshot
Upvotes: 0
Views: 550
Reputation: 26
Your class doesn't have any properties. The line
Public SupplierName As String
creates a field, not a property.
To fix your code do one of the following... either change the class declaration to say
Public Property SupplierName As String
etc...
or change your property reading code to say
Dim p As FieldInfo = item.GetType().GetField(c.ColumnName)
Upvotes: 1
Reputation: 41569
Options:
ColumnName is wrong - doesn't exactly match the name of the property.
There is no public property with the name you're expecting. Maybe its a Field or a Private property.
Maybe update your question with an example of the ColumnName from the DataTable, and also the definition of a class that you're attempting to populate.
Upvotes: 1