2014-02-20 179 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從數據表中的一個例子,也是你正在試圖填充類的定義更新你的問題。