1

我有以下代码来绑定数据库表中的组合框:

Public Sub FillComboBox(ByVal cboCombo As ComboBox, ByVal sSQL As String, ByVal strTable As String, ByVal strDisplayMember As String, ByVal strValueMember As String)
    Dim CN As New OleDbConnection

    Try
        With CN
            If .State = ConnectionState.Open Then .Close()

            .ConnectionString = cnString
            .Open()
        End With

        Dim da As OleDbDataAdapter = New OleDbDataAdapter(sSQL, CN)
        Dim dt As New DataSet

        da.Fill(dt, strTable)

        cboCombo.DataSource = dt.Tables(strTable).DefaultView
        cboCombo.DisplayMember = strDisplayMember
        cboCombo.ValueMember = strValueMember
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        Debug.Print(ex.Message)
    Finally
        CN.Close()
    End Try
End Sub

由于“选择项目”值不是表中记录的一部分,我如何将它添加到组合框中?

4

2 回答 2

3

我认为您可以从中添加一个额外的 Datarow,就像这样。

    Dim da As OleDbDataAdapter = New OleDbDataAdapter(sSQL, CN)
    Dim dt As New DataSet

    da.Fill(dt, strTable)

    cboCombo.DataSource = dt.Tables(strTable).DefaultView
    cboCombo.DisplayMember = strDisplayMember
    cboCombo.ValueMember = strValueMember


    Dim dr As DataRow = dt.Tables(strTable).NewRow()
       dr(0) = "-1"
       dr(1) = "Select Item"
       dt.Tables(strTable).Rows.InsertAt(dr, 0)
       cboCombo.DataBindings.Add("DataSource", dt, dt.Tables(strTable).TableName)
       cboCombo.DataBindings.Clear()
于 2013-02-14T06:27:54.380 回答
0

您可以设置组合框文本。

    cboCombo.DataSource = dt.Tables(strTable).DefaultView
    cboCombo.DisplayMember = strDisplayMember
    cboCombo.ValueMember = strValueMember
    cboCombo.Text = "(select an item)"

另一种方法是datatable在绑定到combobox.

据说有一种使用反射的方法,但我无法让它工作。

于 2013-02-14T05:39:52.050 回答