【问题标题】:Filling a combobox using a query with a where command (VB.NET)使用带有 where 命令的查询填充组合框 (VB.NET)
【发布时间】:2016-08-22 14:02:48
【问题描述】:

我在填充组合框时遇到问题。 我可以用一个简单的选择查询来填写。 现在我想用包含 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

【问题讨论】:

  • Select Sector from Onderaannemers where Naam_firma = @naam 这是你的问题。您在查询中添加了一个参数,但从未在查询中包含一个参数...
  • 那应该怎么做呢?
  • 类似这样的:command.Parameters.Add(New OleDbParameter("@naam", naam-yourvalue)) command = New OleDbCommand(query, connectie)之后执行此操作。另一方面,在访问数据库时处理您建立的连接很重要,我建议将您的命令和连接包装在 using 语句中以确保它们被处理。
  • 谢谢,它成功了。不敢相信我自己没有弄清楚。我使用相同的方法填充数据集。

标签: vb.net combobox


【解决方案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,请告诉我。

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多