ComboBox未显示DisplayMember

时间:2013-07-25 12:43:51

标签: sql sql-server vb.net data-binding combobox

我正在尝试在组合框中显示问题ID,以便在文本框中重现匹配的问题。然而,不是问题ID的出现,我收到的是所有5个问题ID:

  

WCInterface.ucQuestions + QuestionWCInterface.ucQuestions +问题

我的代码:

Private loaded As Boolean = False

Private Sub ucQuestions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    cmbQuestion.DisplayMember = "Question_ID"
    cmbQuestion.ValueMember = "Question_ID"
    cmbQuestion.DataSource = retrieveQuestions() 'when form loads

    loaded = True

End Sub

Private Sub cmbQuestion_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbQuestion.SelectedIndexChanged
    If (loaded) Then

        cmbQuestion.DisplayMember = "Question_ID"
        cmbQuestion.ValueMember = "Question_ID"
        cmbQuestion.DataSource = Nothing 'Resets data source
        cmbQuestion.DataSource = retrieveQuestions() 'when form loads
    End If
End Sub

Public Function retrieveQuestions() As List(Of Question)

    Dim typeList As New List(Of Question)
    Dim Str As String = "SELECT Question_ID, Question_Text FROM Question"
    Try
        Using conn As New SqlClient.SqlConnection(DBConnection)
            conn.Open()
            Using cmdQuery As New SqlClient.SqlCommand(Str, conn)
                Using drResult As SqlClient.SqlDataReader = cmdQuery.ExecuteReader()
                    While drResult.Read
                        typeList.Add(New Question(drResult("Question_ID"), drResult("Question_Text")))
                    End While
                End Using 'Automatically closes connection
            End Using
        End Using

    Catch ex As Exception

        MsgBox("Question List Exception: " & ex.Message & vbNewLine & Str)

    End Try

    Return typeList

End Function

我很感激有关如何显示问题ID的建议,谢谢你

2 个答案:

答案 0 :(得分:1)

您没有发布您的Question类,但DisplayMember和ValueMember字段与Question类中的属性字段不匹配:

看起来应该是这样的:

Public Class Question
  Property QuestionID As Integer
  Property QuestionText As String

  Public Sub New(q_ID As Integer, q_Text As String)
    QuestionID = q_ID
    QuestionText = q_Text
  End Sub
End Class

然后您的数据源属性如下所示:

cmbQuestion.DisplayMember = "QuestionID"
cmbQuestion.ValueMember = "QuestionID"
cmbQuestion.DataSource = retrieveQuestions() 

答案 1 :(得分:0)

您必须先分配数据源,然后指定要显示的字段

cmbQuestion.DataSource = Nothing'重置数据源

表单加载时

cmbQuestion.DataSource = retrieveQuestions()'

cmbQuestion.DisplayMember =“Question_ID”

cmbQuestion.ValueMember =“Question_ID”