2014-02-20 115 views
0

我在vb.net中使用了这段代码。该的PropertyInfo p被出山如无物,即使DataTable的我的列名与类名匹配属性PropertyInfo在vb.net中没有任何东西

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 

,我得到的最终落脚点是一切的一类对象设置为无,因为它不流通如果条件。

嗨乔恩,我已经贴我的课片断下来

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 

和我有栏比赛 dataTable where attributes match with the column names的DataTable。请注意,productcategoryName匹配,但在截图

回答

1

您的课程没有任何属性。该行

Public SupplierName As String 

创建一个字段,而不是一个属性。

要解决你的代码执行下列操作... 一个要么改变类声明说

Public Property SupplierName As String 

等等

或更改属性识别代码说

Dim p As FieldInfo = item.GetType().GetField(c.ColumnName) 
+0

哎呀是的。你是对的,谢谢罗杰和乔恩。两者都是对的 –

1

选项没有看到:

  1. 的ColumnName是错误的 - 没有属性的名称完全一致。

  2. 有没有公共财产与你的名字期待。也许它是一个字段或私人财产。

也许用的ColumnName从数据表中的一个例子,也是你正在试图填充类的定义更新你的问题。