2015-08-24 48 views
0

我想分配數據源的ComboBox,將允許用戶選擇一個成員。我在運行我的應用程序時收到此錯誤:VB.NET - 無法綁定到新的顯示成員

無法綁定到新的顯示成員。 參數名稱:newDisplayMember。

這裏是我的代碼:

Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    'GetAllELData() 
    ddlMember.DataSource = GetMemberList() 
    ddlMember.DisplayMember = "DisplayName" 
    ddlMember.ValueMember = "ID" 


End Sub 

Private Function GetMemberList() As List(Of Member) 
    Dim rval = New List(Of Member) 
    Dim dv As DataView = New DataView 
    Dim myConnString = ConfigurationSettings.AppSettings("ConnString") 

    Try 
     dv = SqlHelper.ExecuteDataset(myConnString, CommandType.StoredProcedure, "spGetData").Tables(0).DefaultView 
    Catch ex As Exception 
     MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK) 
    End Try 

    For Each row As DataRowView In dv 
     Dim mbrNum As String = row.Item("IMMBR_CD").ToString() 
     Dim mbrName As String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row.Item("IMMBR_NM20").ToLower()) 
     Dim mbrState As String = row.Item("IMMBR_ST").ToString() 

     'assigns the member data to the list of members 
     rval.Add(New Member(mbrNum, mbrName, mbrState)) 
    Next 

    Return rval 
End Function 

然後我的類定義:

Public Class Member 
    Public ID As String 
    Public Name As String 
    Public State As String 
    Public DisplayName As String 

    Public Sub New(ByVal i As String, ByVal n As String, ByVal s As String) 
     ID = i 
     Name = n 
     State = s 
     DisplayName = ID & " - " & Name & ", " & State 
    End Sub 

    Public Overrides Function ToString() As String 
     Dim rval As String = ID & " - " & Name & ", " & State 
     Return rval 
    End Function 

    Public Function GetID() As String 
     Return ID 
    End Function 

    Public Function GetName() As String 
     Return Name 
    End Function 

    Public Function GetState() As String 
     Return State 
    End Function 
End Class 

我不知道爲什麼,我發現了錯誤。應用程序按預期正確加載成員,並且在錯誤彈出窗口中單擊「繼續」後工作得很好。我發現的關於錯誤的一切都是爲了讓人們傳遞一個表作爲他們的DataSource而不是像我這樣的自定義類,答案只包含代碼片段,而不是解釋爲什麼會出現問題。

任何人都可以幫我弄清楚這裏有什麼問題嗎?

感謝一大堆!

+1

至少在的WinForms,結合'Fields'不會總是工作一樣。嘗試將它們定義爲屬性。 – Plutonix

+0

解決了這個問題。謝謝! – TheIronCheek

回答

0

錯誤是由直接綁定到字段造成的。將它們定義爲屬性並綁定到屬性解決了問題。

Public ReadOnly Property GetID() As String 
    Get 
     Return Me.ID 
    End Get 
End Property 

Public ReadOnly Property GetName() As String 
    Get 
     Return Me.Name 
    End Get 
End Property 

Public ReadOnly Property GetState() As String 
    Get 
     Return Me.State 
    End Get 
End Property 

Public ReadOnly Property GetDisplayName() As String 
    Get 
     Return Me.DisplayName 
    End Get 
End Property 

和:

Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    'GetAllELData() 
    ddlMember.DataSource = GetMemberList() 
    ddlMember.DisplayMember = "GetDisplayName" 
    ddlMember.ValueMember = "GetID" 


End Sub