VB.NET中如何通过BindingSource过滤TextBox内容并显示到另一个TextBox
解决方案:将过滤后的ITM值显示到TextBoxITM中
要实现把过滤后的ITM列结果显示到TextBoxITM,只需在TextBoxITC_KeyDown事件的过滤成功逻辑里,从BindingSource中提取对应ITM值并赋值给TextBoxITM即可。以下是修改后的完整代码及关键说明:
修改后的代码
Dim source1 As New BindingSource() Private Sub PopulateDatatable() Try Dim query As String = "Select ITC,ITM FROM IFG WHERE GDN = 'A.04.01.002.001'" Using con As OleDbConnection = New OleDbConnection(cn) Using cmd As OleDbCommand = New OleDbCommand(query, con) Using da As New OleDbDataAdapter(cmd) Dim dt As DataTable = New DataTable() da.Fill(dt) source1.DataSource = dt End Using End Using End Using Catch myerror As OleDbException MessageBox.Show("Error: " & myerror.Message) End Try End Sub Private Sub TextBoxITC_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBoxITC.KeyDown If e.KeyCode = Keys.Back Then source1.Filter = "" TextBoxITC.Clear() clearData() ' 确保此方法包含TextBoxITM.Clear() ElseIf e.KeyCode = Keys.Enter Then ' 过滤匹配ITC的记录 source1.Filter = "ITC = '" & Replace(TextBoxITC.Text, "'", "") & "'" If source1.Count <= 0 Then source1.Filter = "" TextBoxITC.Clear() MsgBox("No Result Found!", MsgBoxStyle.Exclamation) clearData() Else ' 从过滤结果中提取ITM值并赋值给TextBoxITM Dim rowView As DataRowView = DirectCast(source1.Item(0), DataRowView) TextBoxITM.Text = rowView("ITM").ToString() End If End If End Sub ' 补充clearData方法(如果未定义) Private Sub clearData() TextBoxITM.Clear() End Sub
关键修改说明
- 显示过滤结果:在
source1.Count > 0的分支中,通过DataRowView获取BindingSource第一条记录的ITM列值,直接赋值给TextBoxITM。 - 逻辑优化:将原有的两个独立
If判断改为ElseIf,避免重复执行逻辑。 - 状态统一:确保
clearData方法包含清空TextBoxITM的操作,保证回退或无结果时界面状态一致。
额外优化建议
- 规避SQL注入:如果后续需要动态修改
GDN参数,改用参数化查询替代字符串拼接:Dim query As String = "Select ITC,ITM FROM IFG WHERE GDN = @GDN" cmd.Parameters.AddWithValue("@GDN", "A.04.01.002.001") - 空值处理:若ITM列可能为空,添加空值判断避免报错:
TextBoxITM.Text = If(rowView("ITM") Is DBNull.Value, "", rowView("ITM").ToString())
内容的提问来源于stack exchange,提问作者roy
相关产品推荐
相关产品推荐

