VB.NET Filter Datagridview based off primary form index field

Ryan Lashway 61 Reputation points
2022-03-29T18:40:25.837+00:00

I can not for the life of me figure this out, or find a solution.

I have a form with a textbox bound to Customer.CustomerID, I am trying to find he best way to filter a datagridview, or its sound sub_CustomerContactInfo on the CustomerID field.

Is there a visual gui method, and if not, how can I complete a filter = sub_CusomerContactInfo.CustomerID = Customer.CustomerID for the current data loaded within the form.

I am sorry and appreciate any assistance.

Developer technologies VB
{count} votes

1 answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2022-03-29T19:31:47.253+00:00

    Hi

    To find a particular value in a DataTable column, assuming you are using a BindingSource, then one example in the TextBox TextChanged event, and BS is a BindingSource on a DataTable:

    BS.Position = BS.Find("Name", TextBox1Text) where "Name" is the field/column name and the search text is whatever TextBox1.Text is.

    A more simple dynamic way, using the DataTable DefaultView:

    myTable.DefaultView.RowFilter = "FirstName Like '" & TextBox1.Text & "'"

    Of course, you would need to adapt to suit.

    EDIT: added a better example. This is a stand alone example and just needs a ListBox1, ComboBox1 and a TextBox1 on Form1.

    188010-111.png

    ' Form1 with CB1 and TB1  
    Option Strict On  
    Option Explicit On  
    Public Class Form1  
      Dim lst As New List(Of String)  
      Dim BS As New BindingSource  
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
        With lst  
          .Add("Being in a stormy relationship is difficult")  
          .Add("a major commitment to storm the white house")  
          .Add("it is in a flurry of a snow storm")  
          .Add("In a Major storm IT was horrific")  
          .Add("that a white out caused a horrific accident")  
        End With  
        BS.DataSource = lst  
        ComboBox1.DataSource = BS  
        ListBox1.DataSource = BS  
      End Sub  
      Function GetDistinctContains(lst As List(Of String)) As List(Of String)  
        ' get Unique, Distinct list(Of String)  
        ' from a  list(Of String) where items  
        ' contain string from a TextBox.Text  
        Dim lst2 As List(Of String) = lst.Where(Function(w As String) w.IndexOf(TextBox1.Text, 0, StringComparison.CurrentCultureIgnoreCase) > -1).Distinct.ToList  
        Return lst2  
      End Function  
      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged  
        BS.DataSource = GetDistinctContains(lst)  
      End Sub  
    End Class  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.