admin

组合框未显示DisplayMember

sql

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

WCInterface.ucQuestions +问题WCInterface.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的任何建议,谢谢


阅读 172

收藏
2021-07-01

共1个答案

admin

您没有发布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()
2021-07-01