使用带有where命令的查询填充组合框(VB.NET)

时间:2016-08-22 14:02:48

标签: vb.net combobox

我在填充组合框时遇到问题。 我可以用一个简单的选择查询填充一个。 现在我想用一个包含where命令的查询填充一个组合框。我尝试了几种解决方案但没有一种方法有效。 如何用带有where语句的查询填充组合框?

到目前为止我的代码是:

 Public Function vulComboboxTesten(box As ComboBox, naam As String) As ComboBox
        box.Items.Clear()
        box.Items.Add(" ")
        Dim query As String
        query = "Select Sector from Onderaannemers where Naam_firma = @naam "
        Debug.WriteLine(query)
        Dim command As OleDbCommand
        command = New OleDbCommand(query, connectie)

        command.Connection.Open()

        Dim datareader As OleDbDataReader
        datareader = command.ExecuteReader

        While datareader.Read
            Dim item As New ComboBoxItem
            item.Content = datareader("Sector")
            box.Items.Add(item)
        End While

        command.Connection.Close()
        Return box
    End Function

1 个答案:

答案 0 :(得分:1)

试试这个先生。我不知道如何将我的代码翻译成您的编码类型。但请阅读解释。

Private Sub StoringDatainCombobox()
    Try
        Dim comboSource As New Dictionary(Of String, String)()
        mkcon() 'this is just my sqlCon.Open
        Dim cmd As New SqlCommand
        Dim rd As SqlDataReader

        cmd.Connection = sqlCon
        cmd.CommandText = "data_get" 'my query stored procedure.
        'cotains something like this select * from tb1 where isactive = true
        cmd.CommandType = CommandType.StoredProcedure

        comboSource.Add(0, "") ' for blank item in the 1st value of combobox
        ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
        ComboBox1.DisplayMember = "Value"
        ComboBox1.ValueMember = "key"
        ComboBox1.Text = ""

        rd = cmd.ExecuteReader
        While (rd.Read)
                comboSource.Add(rd("dataId"), rd("dataName"))
                ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
                ComboBox1.DisplayMember = "Value"
                ComboBox1.ValueMember = "key"
                ComboBox1.Text = ""
        End While
        sqlCon.Close()
    Catch ex As Exception
        MessageBox.Show("Failed." & ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

现在,您还可以使用ID显示查询的数据结果。 如果您需要在用户选择组合框中的项目时如何获取ID,请通知我。

希望这会对你有所帮助。