如何使用SQLite数据读取器创建ComboBox自动填充

时间:2011-04-24 15:11:33

标签: vb.net sqlite

我有两个像这样的组合框

enter image description here

我需要为第一个组合框创建一个自动填充功能。如果Search-By Field指定为Employee-Number,则应列出EmployeeID。同样,如果Search-By字段是Employee-Name,它应该列出Employee First Name和Last Name。

我该怎么做?我不知道,我是第一次这样做。我正在使用SQLite,Visual Studio 2010。

  Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
        Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
        Dim sqConnection As New SQLiteConnection(myConnString)
        Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
        sqConnection.Open()

        Try
            ' Always call Read before accessing data.
            Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
            Dim j As Integer = sqReader.FieldCount
            While sqReader.Read()

'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
                End While

            'Close Reader after use
            sqReader.Close()

        Catch ex As Exception
            'Show Message on Error
            MsgBox(ex.ToString)
        Finally
            'At Last Close the Connection
            sqConnection.Close()
        End Try

2 个答案:

答案 0 :(得分:0)

请注意组合框的以下属性:AutoCompleteMode,AutoCompleteSource,AutoCompleteCustomSource。

选择适当的AutoCompleteMode。在this link查看有关不同模式的详细信息。 对于AutoCompleteSource,选择ListItems(在这种情况下,源将是ComboBox的项目)或CustomSource。如果选择CustomSource,请将相应的源设置为ComboBox的AutoCompleteCustomSource属性的值。

这应该为您提供足够的细节来做您正在寻找的事情。 您列出的其他要求(例如从SQLite数据库获取数据或更改员工姓名和员工编号)不会影响您使用自动完成功能的方式。

答案 1 :(得分:0)

我不确定你在问什么,但我认为就是这样。 在SelectedIndex已更改的事件中,您将获得类似于以下代码的内容。您可以添加If语句来检查您要查询的内容并相应地调整您的查询。

Dim dt as New DataTable

Try
            Using sqlConn

            sqlConn.Open()

                Using cmd As New SqlCommand("your query")

                    cmd.Connection = sqlConn
                    cmd.CommandType = CommandType.Text


                   Dim reader as SqlDataReader = cmd.ExecuteReader()
                   dt.Load(reader)
                End Using


        End Using
    Catch ex As SqlException
        Throw New Exception(ex.Message)
    End Try

With yourComboBox
     .DataSource = dt
     .DataValueField = "columName you want to be the value of the item"
     .DataTextField = "columnName of the text you want displayed"
End With