1

我试图在组合框中显示问题 ID,以便在文本框中重现匹配的问题。但是,我收到的不是问题 ID,而是所有 5 个问题 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 的任何建议,我将不胜感激,谢谢

4

2 回答 2

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() 
于 2013-07-25T18:15:43.117 回答
0

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

cmbQuestion.DataSource = Nothing '重置数据源

cmbQuestion.DataSource = retrieveQuestions() '当表单加载时

cmbQuestion.DisplayMember = "Question_ID"

cmbQuestion.ValueMember = "Question_ID"

于 2013-07-25T15:10:36.937 回答