我创建了一个显示所有数据的Datagridview
。我现在希望能够过滤我的数据。我使用的是DataSet
,BindingSource
和TableAdapter
。我尝试了一些东西,但似乎没有任何效果。目前我有一个TextBox
,应该在编写时进行过滤。当我执行并输入框时,它不会过滤或错误输出。以下是我的代码。我错过了什么吗?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
Dim cn As SqlConnection = New SqlConnection("")
adap = New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
adap.InsertCommand = builder.GetInsertCommand()
'adap.UpdateCommand = builder.GetUpdateCommand()
'adap.DeleteCommand = builder.GetDeleteCommand()
dt = New DataTable()
adap.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = _
String.Format("res_snbr Like '%" & TextBox1.Text) & "%'"
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
答案 0 :(得分:0)
如果你的数据源是一个数据表,你可以试试这个。
TryCast(InventoryDetailsBindingSource, DataTable).DefaultView.RowFilter = String.Format("Field = '{0}'", textBoxFilter.Text)
您可以在数据表上使用行过滤器属性,如下所示。 http://www.csharp-examples.net/dataview-rowfilter/
答案 1 :(得分:0)
Imports System.Data.SqlClient
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
adap.InsertCommand = builder.GetInsertCommand()
adap.Fill(dt)
InventoryDetailsBindingSource.DataSource = dt
DataGridView1.DataSource = InventoryDetailsBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = String.Format("res_snbr Like '%{0}%'", TextBox1.Text)
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
End Class
有很多方法可以完成你想要做的事情,上面的代码是我如何做到的。在其他差异中,请注意BindingSource
用作DataSource
的{{1}},以及设置DataGridView
时正确使用String.Format
Filter
的属性。
干杯!