Providing a filter for your data results in a PowerShell form

I’ve often found myself wanting to provide filtering functionality in my forms for datagridviews that contain a lot of results. The following is what I’ve done to provide filtering functionality.

  1. Have a datagridview that contains one or more columns that you want to be able to filter text in.
  2. Create a timer in your form with an interval of around 500ms. ¬†Create a ‘Tick’ event for the timer with the following:

    filter-timer_tick

    $timer.Stop()
    $datagridview.CurrentCell = $null
    If ($textbox.Text.Length -eq 0)
    {
    	foreach ($row in ($datagridview.Rows))
    	{
    		$datagridview.Rows[$row.Index].Visible = $true
    	}
    }
    Else
    {
    	foreach ($row in ($datagridview.Rows))
    	{
    		If ($row.Cells[$columnIndex/Name].Value -like "$($textbox.Text)*")
    		{
    			$datagridview.Rows[$row.Index].Visible = $true
    		}
    		Else
    		{
    			$datagridview.Rows[$row.Index].Visible = $false
    		}
    	}
    }
  3. Create a textbox within the form, then add a ‘TextChanged’ event with the following:

    filter-textbox_textchanged

    $timer.Stop()
    $timer.Start()

With the above in place if someone starts typing into the textbox and pauses for 500ms, the timer will execute and filter the datagridview for text that’s in the textbox. In the above example I use ‘-like’ when evaluating the cell content so that the use of a wildcard character is controlled by the textbox.

In the event that your datagridview (or data source in general) contains a ton of records, you could improve the experience by moving the actual filtering process to a Job, and then changing the cursor of the form to ‘WaitCursor’ until the job finishes.

Leave a Reply

Your email address will not be published. Required fields are marked *