vb.net 如何将“选择项目”作为第一项绑定组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14867865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:20:09  来源:igfitidea点击:

How to bind combobox with "Select Item" as the first item

vb.netcomboboxvb.net-2010

提问by jaypabs

I have the following code to bind the combobox from the database table:

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

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

Since "Select Item" value is not part of the record from the table, how can I add it in the combobox?

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

回答by Von Aaron

I think you can add an additional Datarow from it, something like this.

我认为您可以从中添加一个额外的 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()

回答by Brian Webster

You can set the combo box text.

您可以设置组合框文本。

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

The alternative is to actually add it to your datatablebefore binding to the combobox.

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

Supposedly there is a methodusing reflection, but I could not get it to work.

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