【发布时间】:2019-12-25 14:31:22
【问题描述】:
尝试根据在 Combobox 中输入的文本将一组数据从数据表填充到 Combobox。但是在数据表的 Select 方法中出现System.Data.DataRow 错误。
以下是在 Form Load 上绑定数据表并在调用 Search 方法时重新绑定数据的代码。
请注意,搜索必须按 Tab 键而不是自动完成
Imports System.Data.SqlClient
Public Class Form1
Dim connection As SqlConnection = New SqlConnection()
Dim table As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadComboBox()
End Sub
Private Sub LoadComboBox()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select stage from sample", connection)
adp.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub Search()
Dim filteredTable As New DataTable
Dim filterRow As DataRow()
Dim str As String = ComboBox1.Text.Trim
filterRow = table.Select("stage like '%" & ComboBox1.Text.ToString & "%'")
'**Error in above table(datatable)**
For Each rw As DataRow In filterRow
filteredTable.ImportRow(rw)
Next
ComboBox1.DataSource = New BindingSource(filteredTable, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub ComboBox1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles ComboBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Search()
End If
End Sub
End Class
【问题讨论】:
-
看看 AutoCompleteMode 和 AutoCompleteSource 是否能满足您的要求。
-
@Mary 此搜索只能在 Tab 按下时发生,因此我没有使用 AutoCompleteMode 或 AutoCompleteSource。
-
你在哪里声明了表?
-
@Mary 表在 Form1 类中声明