过滤DataGridView

时间:2017-10-26 16:51:42

标签: vb.net datagridview

我在winform中有一个DataGridView以及一个TextBox,可以在DataGridView中搜索。 DataGridView有一个CheckBox列。这就是我的代码的样子:

 Imports System.ComponentModel
 imports system.Data.sqlclient

 Public Class MyForm
    Dim con As New SqlConnection("Data source=" & My.Settings.sqlserver & ", " & My.Settings.sqlport & ";Network Library=DBMSSOCN;initial catalog=" & My.Settings.dbname & ";User id=" & My.Settings.Username & ";Password=" & My.Settings.Password & ";")

    Dim ds As New DataSet

    Private Sub filterdata(valuetosearch As String)
        Dim srq As String = "Select * from Contacts where CONCAT([Unique id],Prefix,[First name],[Last name],Gender,Title,Company,Phone,Mobile,Fax,[b.email],[p.email],Reference,Address,[Address 2],Country,City,Zip,Facebook,GooglePlus,Instagram,Twitter,Website,Salary,Currency,[Group],[Id/Status],Note,[Added by]) like '%" & valuetosearch & "%' "
         Dim adapter As New SqlDataAdapter(srq, con)
         adapter.Fill(ds, "Contacts_table")
         userdatagrid.DataSource = ds.Tables(0)
   End Sub
   Private Sub searcgcon_TextChanged(sender As Object, e As EventArgs) Handles searcgcon.TextChanged
       If searcgcon.Text = "" Then
           filterdata("")
           entrylabel.Text = "There are/is " & userdatagrid.Rows.Count & " contact entries"
      Else
         filterdata(searcgcon.Text)
         entrylabel.Text = "There are/is " & userdatagrid.Rows.Count & " contact entries that contain your query :" & searcgcon.Text
      End If
  End Sub

  Private sub refresh_click()handles refresh.click
      filterdata("")
  end sub
 End class

我已纠正过早期的问题(请参阅How to maintain datagridview checkstate when filtering VB.net)。

现在我遇到的问题是当我按下触发" filterdata"的按钮时,例如刷新按钮或甚至当我在TextBox(用于过滤的那个)中单击/键入内容时,DataGridView会不断添加相同数据的行。请告诉我哪里错了。

我在其他网站上发布了此内容。一个人说我的filterdata代码应该采用加载事件的形式。如果我这样做,那么我将遇到一些问题,如:

  1. 我没有名为filterdata的子

  2. 如果我没有该子文件,我应该如何在TextBox TextChanged事件中使用它?

  3. 如果我仍然错了,请纠正我。我只是个学生!

    (PS数据库包含一个Image列,我不能将其包含在srq字符串中,因为它在adapter.fill上给我一个错误说"操作数类型冲突:图像与nvarchar不兼容" )

1 个答案:

答案 0 :(得分:1)

使用以下代码更新您的filterdata方法 -

Private Sub filterdata(valuetosearch As String)
    userdatagrid.DataSource = Nothing
    Dim ds As New DataSet
    Dim srq As String = "Select * from Contacts where CONCAT([Unique id],Prefix,[First name],[Last name],Gender,Title,Company,Phone,Mobile,Fax,[b.email],[p.email],Reference,Address,[Address 2],Country,City,Zip,Facebook,GooglePlus,Instagram,Twitter,Website,Salary,Currency,[Group],[Id/Status],Note,[Added by]) like '%" & valuetosearch & "%' "
    Dim adapter As New SqlDataAdapter(srq, con)
    adapter.Fill(ds, "Contacts_table")
    userdatagrid.DataSource = ds.Tables(0)
End Sub

您必须在每次文本更改时重置数据集和网格数据源。