Results 1 to 9 of 9

Thread: Datagridview: filenames with bindingsource filter

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Datagridview: filenames with bindingsource filter

    I have a datagridview1 and search textbox1 on my form

    On form load I need to fill datagridview1

    * with absolute path+filename of certain filetypes like *.jpg,png,gif,bmp
    * in a specific directory like Application.StartupPath & "\Images"



    When user types in search textbox1

    * datagridview1 contents need to be continuously filtered to match searchstring


    Can anyone please tell me with the code to achieve this.


    Thanks

  2. #2
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Datagridview: filenames with bindingsource filter

    Here is something to get you started
    vb.net Code:
    1. 'Declare a bindingsource variable with class scope
    2. Private myBindingSource As New BindingSource
    3.  
    4. 'Call this sub to populate your datagridview. In form.load event maybe?
    5. Private Sub PopulateDatagridView(ByVal folderPath As String)
    6.         'Create a datatable to hold your files data
    7.         Dim table As New DataTable()
    8.         With table
    9.             .Columns.Add("Name", GetType(String))
    10.             .Columns.Add("Directory", GetType(String))
    11.             .Columns.Add("FileSize", GetType(Long))
    12.         End With
    13.  
    14.         'Declare an array of file extensions, add more if needed
    15.         Dim exts As String() = {"*.jpg", "*.png", "*.bmp"}
    16.  
    17.         'Create a directoryinfo object
    18.         Dim dirInfo As New IO.DirectoryInfo(folderPath)
    19.  
    20.         'Loop thru the extension array and get files for each extension type
    21.         Dim files As IO.FileInfo() = Nothing
    22.         For Each ext As String In exts
    23.             files = dirInfo.GetFiles(ext, System.IO.SearchOption.AllDirectories)
    24.             'loop thru the fileinfo array and add rows to datatable
    25.             For Each fi As IO.FileInfo In files
    26.                 table.Rows.Add(fi.Name, fi.Directory, fi.Length)
    27.             Next
    28.         Next
    29.  
    30.         'Bind the table to the bindingsource, then the bindingsource to the datagridview
    31.         Me.myBindingSource.DataSource = table
    32.         DataGridView1.DataSource = Me.myBindingSource
    33.  
    34.     End Sub
    35.  
    36.  
    37. 'Handle the textchanged event of your textbox and set the bindingsource filter accordingly
    38. Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    39.         Dim txt As String = TextBox1.Text
    40.         If String.IsNullOrEmpty(txt) Then
    41.             Me.myBindingSource.RemoveFilter()
    42.         Else
    43.             Me.myBindingSource.Filter = "Name Like '" & txt & "%'"
    44.         End If
    45.     End Sub
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Re: Datagridview: filenames with bindingsource filter

    Thanks stanav. I'm new on these forums. How can I copy your code without getting the line numbers ?

  4. #4
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Datagridview: filenames with bindingsource filter

    Quote Originally Posted by Xancholy
    Thanks stanav. I'm new on these forums. How can I copy your code without getting the line numbers ?
    You click on "Quote" button as if you're replying to the post, then copy from the reply text box.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Resolved Re: Datagridview: filenames with bindingsource filter

    Quote Originally Posted by stanav
    Here is something to get you started
    Get me started ?? This worked perfectly out of the box And you gave me directory & filesize columns to boot ! Thanks stanav.

    Reader, just remember to add
    Code:
    Imports Microsoft.VisualBasic.FileIO
    Call the code by:
    Code:
    PopulateDatagridView(SpecialDirectories.MyPictures)
    and if you want to search anywhere in the filename use this:
    Code:
    Me.myBindingSource.Filter = "Name Like '%" & txt & "%'"
    stanav, if the dgv is filled with 1000s of items, how can I optimize the search so that textchanged is not firing as user is typing ? something like the itunes search filter...
    Last edited by Xancholy; Jun 3rd, 2008 at 03:45 PM.

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Re: Datagridview: filenames with bindingsource filter

    Also, can you please show me how to cycle through the datagridview rows and fill a listview with the image in each datagridview row ?

    The only catch is that when filter is removed the listview contents has to return to displaying all files in the directory.
    Last edited by Xancholy; Jun 3rd, 2008 at 03:45 PM.

  7. #7
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Datagridview: filenames with bindingsource filter

    How does the itunes search filter work? I've never used itunes so I don't know anything about it...
    Look at various events of the TextBox control and handle the one that most fits your need.
    And you actually don't have to Imports Microsoft.VisualBasic.FileIO for the code I provided. I already qualified the class name, given that the System namespace is imported by default. If you're to import it, you should import System.IO namespace instead of Microsoft.VisualBasic.FileIO
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  8. #8

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    515

    Re: Datagridview: filenames with bindingsource filter

    I stand corrected about System.IO namespace.

    Here's how the winamp filter works (not very well, avoid at all costs)

    If you use winamp and have tens of thousands of songs. Calling up the F3 search and start to type.. uh, something like "arctic"..
    10,000 tunes
    type A
    app searches on A
    list contains 9500 entries, took 1 second
    type R
    app searches on AR
    list contains 6500 entries

    To avoid this something like this:
    Code:
    Private actionCounter as Integer = 5
    
    Sub TextBox1_TextChanged(whatever) Handles TextBox1.TextChanged
      actionCounter = 5
      timer1.Enabled = True
    End Sub
    
    Sub Timer1_Tick(whatever) Handles Timer1.Tick
      actionCounter -= 1
      If actionCounter > 0 Then Return
    
      timer1.Enabled = false 'stop firing events now user stopped typing
    
      dgvBS.Filter = String.Format("[FileName] LIKE '*.{0}'", extensionTextbox.Text)
    
    End Sub
    every time the user presses a key, I start a timer (whose interval is set to 100) and reset a counter to 5
    Every timer tick, decrement the counter by 1. If the counter is 0, then run the search

    This way the search only runs half a second after the last time the user pressed the key. Most users can type faster than one key per half second, so you dont end up with a UI that makes 5 list refinements if the user types 5 chars..

    I feel itunes pretty much works like this.
    Is there a better way??

    Also can you please show me how to populate a imagelist with the images from the bindingsource as it filters ?
    Last edited by Xancholy; Jun 3rd, 2008 at 07:10 PM.

  9. #9
    Member
    Join Date
    Apr 2011
    Posts
    33

    Re: Datagridview: filenames with bindingsource filter

    good code filter datagridview


    1 form1
    2 combobox
    3 textbox
    4 detagridview


    Option Explicit On
    Option Strict On

    ' espacio de nombres para poder acceder al cliente sql
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Data.OleDb


    Public Class Form1
    Dim cs As New OleDb.OleDbConnection
    ' enumeración para las opciones que se usarán
    ' para filtrar con el operador Like
    Enum e_FILTER_OPTION
    SIN_FILTRO = 0
    CADENA_QUE_COMIENCE_CON = 1
    CADENA_QUE_NO_COMIENCE_CON = 2
    CADENA_QUE_CONTENGA = 3
    CADENA_QUE_NO_CONTENGA = 4
    CADENA_IGUAL = 5
    End Enum
    ' cadena de conexión para SQL EXPRESS en modo local

    'Instanciar el componente BindingSource
    Private BindingSource1 As Windows.Forms.BindingSource = New BindingSource

    Private Sub Form1_Load( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
    'cs.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = |DataDirectory|\ipuctesoreria.accdb"
    Dim cs As New OleDb.OleDbConnection("provider=Microsoft.ACE.oledb.12.0;data source = |DataDirectory|\ipuctesoreria.accdb;Persist Security Info=False;")

    Try
    ' Inicializar la conexión y abrir
    Using cn As OleDbConnection = cs
    cn.Open()

    ' Inicializar DataAdapter indicando el sql para recuperar
    'los registros de la tabla
    Dim da As New OleDbDataAdapter("SELECT * FROM junta_local_ofrendas", cn)
    Dim dt As New DataTable ' crear un DataTable

    ' llenarlo
    da.Fill(dt)

    ' enlazar el DataTable al BindingSource
    BindingSource1.DataSource = dt

    ' agregar las opciones al combobox
    With (ComboBox1)

    'cargar los items de opciones para filtrar
    .Items.Add("No filtrar")
    .Items.Add("Que comience con")
    .Items.Add("Que No comience con")
    .Items.Add("Que contenga")
    .Items.Add("Que No contenga")
    .Items.Add("Que sea igual")

    .DropDownStyle = ComboBoxStyle.DropDownList
    .SelectedIndex = 1
    End With
    End Using
    ' errores
    Catch ex As Exception
    MsgBox(ex.Message.ToString)
    End Try
    End Sub


    Private Sub Aplicar_Filtro()

    ' filtrar por el campo Producto
    ''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim ret As Integer = Filtrar_DataGridView( _
    "concepto_ofrenda", _
    TextBox1.Text.Trim, _
    BindingSource1, _
    DataGridView1, _
    CType(ComboBox1.SelectedIndex, e_FILTER_OPTION))

    If ret = 0 Then
    ' si no hay registros cambiar el color del txtbox
    TextBox1.BackColor = Color.Red
    Else
    TextBox1.BackColor = Color.White
    End If
    ' visualizar la cantidad de registros
    Me.Text = ret & " Registros encontrados"

    End Sub

    Function Filtrar_DataGridView( _
    ByVal Columna As String, _
    ByVal texto As String, _
    ByVal BindingSource As BindingSource, _
    ByVal DataGridView As DataGridView, _
    Optional ByVal Opcion_Filtro As e_FILTER_OPTION = Nothing) As Integer

    ' verificar que el DataSource no esté vacio
    If BindingSource1.DataSource Is Nothing Then
    Return 0
    End If

    Try

    Dim filtro As String = String.Empty

    ' Seleccionar la opción
    Select Case Opcion_Filtro
    Case e_FILTER_OPTION.CADENA_QUE_COMIENCE_CON
    filtro = "like '" & texto.Trim & "%'"
    Case e_FILTER_OPTION.CADENA_QUE_NO_COMIENCE_CON
    filtro = "Not like '" & texto.Trim & "%'"
    Case e_FILTER_OPTION.CADENA_QUE_NO_CONTENGA
    filtro = "Not like '%" & texto.Trim & "%'"
    Case e_FILTER_OPTION.CADENA_QUE_CONTENGA
    filtro = "like '%" & texto.Trim & "%'"
    Case e_FILTER_OPTION.CADENA_IGUAL
    filtro = "='" & texto.Trim & "'"
    End Select
    ' Opción para no filtrar
    If Opcion_Filtro = e_FILTER_OPTION.SIN_FILTRO Then
    filtro = String.Empty
    End If

    ' armar el sql
    If filtro <> String.Empty Then
    filtro = "[" & Columna & "]" & filtro
    End If

    ' asigar el criterio a la propiedad Filter del BindingSource
    BindingSource.Filter = filtro
    ' enlzar el datagridview al BindingSource
    DataGridView.DataSource = BindingSource.DataSource

    ' retornar la cantidad de registros encontrados
    Return BindingSource.Count

    ' errores
    Catch ex As Exception
    MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)
    End Try

    Return 0

    End Function

    Private Sub txt_Filtro_TextChanged( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles textbox1.TextChanged

    Aplicar_Filtro()

    End Sub
    End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width