|
-
Jun 3rd, 2008, 01:42 PM
#1
Thread Starter
Fanatic Member
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
-
Jun 3rd, 2008, 03:08 PM
#2
Re: Datagridview: filenames with bindingsource filter
Here is something to get you started
vb.net Code:
'Declare a bindingsource variable with class scope
Private myBindingSource As New BindingSource
'Call this sub to populate your datagridview. In form.load event maybe?
Private Sub PopulateDatagridView(ByVal folderPath As String)
'Create a datatable to hold your files data
Dim table As New DataTable()
With table
.Columns.Add("Name", GetType(String))
.Columns.Add("Directory", GetType(String))
.Columns.Add("FileSize", GetType(Long))
End With
'Declare an array of file extensions, add more if needed
Dim exts As String() = {"*.jpg", "*.png", "*.bmp"}
'Create a directoryinfo object
Dim dirInfo As New IO.DirectoryInfo(folderPath)
'Loop thru the extension array and get files for each extension type
Dim files As IO.FileInfo() = Nothing
For Each ext As String In exts
files = dirInfo.GetFiles(ext, System.IO.SearchOption.AllDirectories)
'loop thru the fileinfo array and add rows to datatable
For Each fi As IO.FileInfo In files
table.Rows.Add(fi.Name, fi.Directory, fi.Length)
Next
Next
'Bind the table to the bindingsource, then the bindingsource to the datagridview
Me.myBindingSource.DataSource = table
DataGridView1.DataSource = Me.myBindingSource
End Sub
'Handle the textchanged event of your textbox and set the bindingsource filter accordingly
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim txt As String = TextBox1.Text
If String.IsNullOrEmpty(txt) Then
Me.myBindingSource.RemoveFilter()
Else
Me.myBindingSource.Filter = "Name Like '" & txt & "%'"
End If
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 -
-
Jun 3rd, 2008, 03:18 PM
#3
Thread Starter
Fanatic Member
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 ?
-
Jun 3rd, 2008, 03:20 PM
#4
Re: Datagridview: filenames with bindingsource filter
 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 -
-
Jun 3rd, 2008, 03:27 PM
#5
Thread Starter
Fanatic Member
Re: Datagridview: filenames with bindingsource filter
 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.
-
Jun 3rd, 2008, 03:40 PM
#6
Thread Starter
Fanatic Member
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.
-
Jun 3rd, 2008, 03:50 PM
#7
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 -
-
Jun 3rd, 2008, 05:28 PM
#8
Thread Starter
Fanatic Member
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.
-
Apr 12th, 2011, 01:22 PM
#9
Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|