<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>virtual Archive - Robert Skibbe</title>
	<atom:link href="https://robbelroot.de/blog/tag/virtual/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>alias RobbelRoot – Freelance Full Stack Developer .NET</description>
	<lastBuildDate>Thu, 18 Jan 2024 00:55:45 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://robbelroot.de/wp-content/uploads/2020/12/cropped-favicon-32x32.png</url>
	<title>virtual Archive - Robert Skibbe</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to create a VB NET DataGridView filter functionality in 2024</title>
		<link>https://robbelroot.de/blog/creating-a-vb-net-datagridview-filter-functionality/</link>
					<comments>https://robbelroot.de/blog/creating-a-vb-net-datagridview-filter-functionality/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sun, 13 Feb 2022 06:47:45 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET (EN)]]></category>
		<category><![CDATA[Visual Basic .NET troubleshooting]]></category>
		<category><![CDATA[bound]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[datagrid]]></category>
		<category><![CDATA[datagridview]]></category>
		<category><![CDATA[dataview]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[filtering]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[functionality]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[raw]]></category>
		<category><![CDATA[row]]></category>
		<category><![CDATA[rows]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[selection]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tabular]]></category>
		<category><![CDATA[unbound]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[view]]></category>
		<category><![CDATA[virtual]]></category>
		<category><![CDATA[visual basic]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=9013</guid>

					<description><![CDATA[<p>How to make a VB NET DataGridView filter!? I welcome you to todays post on &#8222;How to make a VB NET DataGridView filter&#8222;! Maybe you came across randomly, or you actively searched for that typical issue. If you&#8217;ve searched it, well theres no big surprise, because it&#8217;s one well known &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/creating-a-vb-net-datagridview-filter-functionality/">How to create a VB NET DataGridView filter functionality in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-functionality.jpg"><img fetchpriority="high" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-functionality.jpg" alt="VB NET DataGridView filter functionality" class="wp-image-9016" title="VB NET DataGridView filter functionality"/></a><figcaption class="wp-element-caption">VB NET DataGridView filter functionality</figcaption></figure>






<h2 class="wp-block-heading" id="how-to-make-a-vb-net-datagridview-filter">How to make a VB NET DataGridView filter!?</h2>



<p>I <strong>welcome </strong>you to todays post on &#8222;How to make a <strong>VB NET DataGridView filter</strong>&#8222;!</p>



<p><strong>Maybe</strong> you <strong>came across </strong>randomly, <strong>or </strong>you actively <strong>searched </strong>for that typical issue.</p>



<p><strong>If </strong>you&#8217;ve <strong>searched </strong>it, well theres <strong>no big surprise</strong>, because it&#8217;s one <strong>well known problem</strong>.</p>



<p><strong>Literally every</strong> (VB NET) <strong>Developer </strong>will face this issue <strong>from time to time</strong>, or <strong>even more than once</strong>.</p>



<p><strong>Usually </strong>you have that <strong>typical user interface</strong> <strong>with </strong>some kind of <strong>listing</strong>, whether it&#8217;s a typical <strong>table </strong>(hence a <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.windows.forms.datagridview" target="_blank" rel="noreferrer noopener">DataGridView</a></strong>) <strong>or it&#8217;s based on tiles</strong>.</p>



<p>If the <strong>user </strong>will then <strong>click </strong>on one of those <strong>rows or tiles</strong>, you <strong>will </strong>mostly <strong>show </strong>some fancy <strong>dialog </strong>thingy, <strong>to edit </strong>this data.</p>



<p><strong>After </strong>the <strong>user </strong>has <strong>finished working </strong>on that detail dialog, it will usually <strong>close and save </strong>the <strong>changed data </strong>back to the data source.</p>



<h3 class="wp-block-heading" id="preview-of-what-we-are-going-to-build">Preview of what we are going to build</h3>



<p>As I&#8217;m a <strong>fan of action instead</strong> of <strong>talking </strong>only, here&#8217;s a <strong>brief example</strong> of what we are going to build.</p>



<p>We will have <strong>a basic form</strong> split in <strong>two areas</strong>:</p>



<ul class="wp-block-list">
<li><strong>One area for </strong>some sort of <strong>search inputs</strong> (add as much as you like)</li>



<li>The second area is an auto <strong>growing / shrinking datagridview</strong></li>
</ul>



<p>You can <strong>enter </strong>a specific <strong>search text</strong> <strong>and </strong>then <strong>confirm </strong>the search by <strong>pressing enter</strong> <strong>or </strong>the corresponding <strong>button</strong>.</p>



<p>There will be <strong>some kind of reset</strong> functionality by <strong>clicking </strong>the &#8222;<strong>X</strong>&#8222;-button, or by using the <strong>escape key</strong>.</p>



<figure class="wp-block-image size-full" id="application-preview"><a href="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-Filter-Application-Preview-1.gif"><img decoding="async" width="799" height="481" src="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-Filter-Application-Preview-1.gif" alt="VB NET DataGridView Filter Application Preview" class="wp-image-9058" title="VB NET DataGridView Filter Application Preview"/></a><figcaption class="wp-element-caption">VB NET DataGridView Filter Application Preview</figcaption></figure>



<h3 class="wp-block-heading" id="one-very-basic-task">One very basic task</h3>



<p>So it&#8217;s <strong>actually</strong> one of the big <strong>basic tasks</strong>, you need to understand in <strong>detail</strong>.</p>



<p>In <strong>this post</strong>, you will get a <strong>nice datagridview filtering</strong> example with some <strong>sub-steps</strong>.</p>



<p>This will consist of <strong>acquiring data </strong>from the very base, over <strong>creating </strong>a nice <strong>GUI to </strong>get user <strong>input </strong>and at last <strong>filtering </strong>that <strong>data</strong>.</p>



<p>To <strong>actually search </strong>for anything, you will <strong>need </strong>some kind of <strong>data source</strong>, right!?</p>



<p>Some <strong>sweet spot</strong>, <strong>where </strong>the <strong>data is </strong>actually <strong>coming from</strong>, <strong>whether </strong>it&#8217;s</p>



<ul class="wp-block-list">
<li>A <strong>database</strong>-ish thingy</li>



<li>Some &#8222;<strong>In-Memory</strong>&#8220; cache</li>



<li>Or <strong>maybe </strong>some <strong>file</strong> based <strong>storage </strong>like a <strong>text file</strong></li>
</ul>



<p><strong>Otherwise </strong>it would be kinda <strong>hard </strong>to actually find out:</p>



<ul class="wp-block-list">
<li><strong>when </strong>to retrieve data?</li>



<li>from <strong>where</strong>?</li>



<li>or most <strong>importantly </strong>&#8211; <strong>how</strong>?</li>
</ul>



<h3 class="wp-block-heading" id="thinking-about-structure">Thinking about structure</h3>



<p><strong>Surely </strong>you should <strong>structure </strong>your <strong>application </strong>in a <strong>properly </strong>designed way &#8211; like always!</p>



<p>What I&#8217;m talking about is: Using <strong>interfaces for abstracting </strong>away implementation details.</p>



<p>This <strong>makes </strong>our <strong>application </strong>much more <strong>flexible </strong>thus being able to switch out dependencies easily.</p>



<p>Or something like <strong>dependency injection</strong>, <strong>to provide</strong> needed <strong>dependencies </strong>from the outside.</p>



<p>With this approach, we <strong>can avoid hardcoding dependencies </strong>inside the classes themselves.</p>



<p>But we <strong>will dive </strong>much <strong>deeper </strong>on that <strong>in separate </strong>blog <strong>posts</strong>, so i may <strong>only touch </strong>the very <strong>basics </strong>here – if at all &#x1f937;&#x200d;&#x2642;&#xfe0f;.</p>



<h2 class="wp-block-heading" id="different-situations-require-different-solutions">Different situations require different solutions</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-Different-initial-situations.jpg"><img decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-Different-initial-situations.jpg" alt="VB NET DataGridView filter - Different initial situations" class="wp-image-9131" title="VB NET DataGridView filter - Different initial situations"/></a><figcaption class="wp-element-caption">VB NET DataGridView filter &#8211; Different initial situations</figcaption></figure>



<p>As you might know, <strong>there are quite a few</strong> different <strong>situations </strong>of <strong>having data inside </strong>your <strong>DataGridView</strong>.</p>



<p>The <strong>3 methods below</strong> are the ones I&#8217;ve seen the most:</p>



<ul class="wp-block-list">
<li><strong>Adding </strong>data <strong>directly</strong></li>



<li>A <strong>list of objects </strong>as source</li>



<li>The thing called <strong>DataView</strong></li>
</ul>



<p>To <strong>elaborate on </strong>this further: <strong>Basically </strong>you have <strong>3 modes</strong> to work with the DataGridView.</p>



<p>Keep in mind, that <strong>those 3</strong> here <strong>don&#8217;t necessarily match up</strong> to the ones above, <strong>as 2</strong> of the ones above <strong>are </strong>basically <strong>bound</strong>.</p>



<ul class="wp-block-list">
<li><strong>Unbound</strong></li>



<li><strong>Bound</strong></li>



<li><strong>Virtual</strong></li>
</ul>



<p>You can <strong>find more </strong>detailed <strong>information </strong>on that, you can <strong><a href="https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/data-display-modes-in-the-windows-forms-datagridview-control" target="_blank" rel="noreferrer noopener">visit the microsoft documentation</a></strong> for that.</p>



<p><strong>Honestly </strong>I would <strong>recommend </strong>you reading <strong>my example implementations</strong> as they are much <strong>easier </strong>to understand and follow.</p>



<h3 class="wp-block-heading" id="adding-data-directly-to-the-datagridview-don-t">Adding data directly to the DataGridView – Don&#8217;t!</h3>



<p>The <strong>easiest </strong>and most <strong>beginner friendliest way </strong>is to <strong>directly add </strong>your <strong>data </strong>to the DataGridView.</p>



<p>This is <strong>done by calling </strong>some kind of &#8222;CollectionThingy.<strong>Add</strong>&#8220; <strong>functionality</strong>.</p>



<p><strong>Even though </strong>this <strong>seems </strong>to be the easy &#8222;Hey, I could just go like this&#8220; way, it <strong>isn&#8217;t</strong> necessarily <strong>the best one</strong>.</p>



<p>I&#8217;m <strong>talking about structuring</strong> and especially about <strong>maintaining and advancing </strong>development.</p>



<p>I&#8217;ve <strong>seen myself struggling through </strong>other developers <strong>chaotic </strong>&#8222;DataGridView.Rows.<strong>Add</strong>&#8220; <strong>code </strong>so many times.</p>



<p>So I would <strong>highly </strong>(really) <strong>recommend </strong>you <strong>not to do it this way</strong>!</p>



<h3 class="wp-block-heading" id="using-a-list-as-datasource">Using a list as datasource</h3>



<p><strong>Using </strong>a <strong>pure list</strong> – a special one – is <strong>actually my </strong>personally <strong>most used </strong>style of populating a DataGridView.</p>



<p><strong>Therefore </strong>I also like to <strong>filter</strong> the <strong>data directly </strong>by using that list, <strong>instead of </strong>operating on those DataGridView <strong>rows </strong>themselves.</p>



<p>This <strong>works strongly typed </strong>and is (at least in my opinion) <strong>easy </strong>to implement.</p>



<p>It also <strong>feels kinda clean</strong> like &#8222;filtering customers by filtering customers&#8220; you know what I mean!?</p>



<p>I would <strong>recommend this </strong>method <strong>and </strong>this is <strong>actually </strong>the <strong>method </strong>we&#8217;re <strong>using in our first example</strong> here.</p>



<h3 class="wp-block-heading" id="utilizing-a-dataview">Utilizing a DataView</h3>



<p>This is actually my <strong>personally least used method of filtering</strong> or populating <strong>data </strong>inside a DataGridView.</p>



<p><strong>Honestly </strong>I <strong>can&#8217;t</strong> even <strong>remember when </strong>I <strong>used </strong>that method the last time so..</p>



<p><strong>Maybe </strong>I&#8217;ll <strong>add some example </strong>of using this at a <strong>later </strong>point, because I want to <strong>focus on </strong>the <strong>most used </strong>style first.</p>



<h2 class="wp-block-heading" id="using-a-bound-list-for-a-vb-net-datagridview-filter">Using a bound list for a VB NET DataGridView filter</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-A-basic-way.jpg"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-A-basic-way.jpg" alt="VB NET DataGridView filter - A basic way" class="wp-image-9049" title="VB NET DataGridView filter - A basic way"/></a><figcaption class="wp-element-caption">VB NET DataGridView filter &#8211; A basic way</figcaption></figure>



<p>So in the <strong>very first</strong> and most &#8222;natural&#8220; kind of <strong>DataGridView filter example</strong>, we will touch the clean basics.</p>



<p>In a few moments, you <strong>will understand </strong>this &#8222;<strong>clean</strong>&#8220; &amp; &#8222;<strong>natural</strong>&#8220; thing <strong>and </strong>the &#8222;<strong>why&#8220; </strong>behind that.</p>



<p>I think that <strong>this </strong>is actually <strong>one of the easiest ways</strong> to understand, as there are <strong>no </strong>fancy or <strong>complex </strong>other <strong>tools </strong>involved.</p>



<p>But well, <strong>one additional</strong> &#8222;<strong>helper</strong>&#8220; <strong>is </strong>actually <strong>used</strong>, as we are in the need of some kind of <strong>listing functionality</strong>.</p>



<p>This <strong>listing thing is </strong>actually <strong>responsible for holding </strong>those different <strong>entries and </strong>being able to <strong>communicate </strong>it&#8217;s internal <strong>changes</strong>.</p>



<p>With <strong>those communication skills</strong>, the <strong>outer </strong>world <strong>can react </strong>to changes <strong>by </strong>like <strong>refreshing </strong>their <strong>graphical representation</strong>.</p>



<h3 class="wp-block-heading" id="an-easy-and-clean-data-source-an-extended-bindinglist">An easy and clean data source – An extended BindingList</h3>



<p>So in this <strong>very first example</strong> we will use a basic <strong>BindingList</strong> as indirect data source.</p>



<p>As <strong>I really prefer</strong> the <strong>object oriented way</strong> the most, we will <strong>create </strong>the <strong>data based on </strong>defined class <strong>instances</strong>.</p>



<p>This <strong>means </strong>we will <strong>need a class</strong> to create some kind of <strong>blueprint</strong>, that <strong>enables </strong>us <strong>encapsulating </strong>the needed data.</p>



<p><strong>After </strong>that and after <strong>instantiating </strong>some <strong>objects</strong>, we can <strong>tell </strong>the <strong>DataGridView </strong>to <strong>display </strong>the data.</p>



<p>Or <strong>better said</strong>, we can tell the grid to <strong>use these</strong> object <strong>instances as datasource</strong> – nice!</p>



<p><strong>One </strong>big <strong>problem </strong>with the default <a href="https://docs.microsoft.com/de-de/dotnet/api/system.componentmodel.bindinglist-1" target="_blank" rel="noreferrer noopener">BindingList</a> class is, that you <strong>can&#8217;t</strong> really <strong>add multiple items </strong>at once.</p>



<p>As <strong>you will see later</strong>, we will <strong>need that </strong>functionality, so we will <strong>define </strong>a small <strong>helper extension method</strong> first.</p>



<p><strong>Create </strong>a <strong>folder </strong>called &#8222;<strong>Utils</strong>&#8222;, put the <strong>following class </strong>inside and <strong>watch out for namespacing</strong> issues:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Namespace Utils

    Module BindingListExtensions

        &lt;Extension()>
        Public Sub AddRange(Of T)(bindingList As BindingList(Of T), collection As IEnumerable(Of T))
            Dim oldRaiseEvents = bindingList.RaiseListChangedEvents
            bindingList.RaiseListChangedEvents = False
            Try
                For Each item In collection
                    bindingList.Add(item)
                Next
            Finally
                bindingList.RaiseListChangedEvents = oldRaiseEvents
                If bindingList.RaiseListChangedEvents Then
                    bindingList.ResetBindings()
                End If
            End Try
        End Sub

    End Module

End Namespace</pre>



<p>With <strong>this BindingList</strong> class <strong>extending </strong>functionality, we will be able to <strong>add multiple items</strong>.</p>



<p>In addition, this <strong>won&#8217;t trigger</strong> a &#8222;Hey I&#8217;ve changed&#8220;-<strong>notification </strong>for each add, <strong>this would be inefficient</strong>.</p>



<p><strong>Imagine </strong>you would be <strong>adding 30000 items</strong> and therefore 30000 change notifications would be triggered.</p>



<p><strong>Wouldn&#8217;t it</strong> simply <strong>be enough</strong> to <strong>add </strong>those <strong>elements and notify </strong>about a change of this list <strong>after </strong>all <strong>work </strong>has been <strong>done </strong>– meaning <strong>once</strong>!?</p>



<p>For this to work, we <strong>need to disable</strong> the <strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.bindingsource.raiselistchangedevents" target="_blank" rel="noreferrer noopener">&#8222;RaiseListChangedEvents&#8220;-property</a></strong> <strong>temporarily</strong>, or <strong>as long </strong>as the adding <strong>process </strong>is <strong>ongoing</strong>.</p>



<p>As this is <strong>one very basic requirement</strong> for many projects, you <strong>should </strong>really be <strong>saving </strong>that <strong>extension method </strong>somewhere &#x1f61b;!</p>



<p>Let&#8217;s go to the <strong>next step</strong> of making that <strong>VB NET DataGridView filter</strong> functionality!</p>



<h3 class="wp-block-heading" id="creating-the-customer-class">Creating the customer class</h3>



<p>So let&#8217;s <strong>now go ahead and</strong> actually <strong>create </strong>this blueprint <strong>class </strong>called &#8222;<strong>Customer</strong>&#8220; for our first example.</p>



<p>I mean seriously, who doesn&#8217;t like <strong>working with (good, on time paying) customers</strong> &#x1f61b;.</p>



<p><strong>Keep in mind</strong>, that <strong>this example</strong> will <strong>only contain</strong> like <strong>basic data</strong> and no deep structures.</p>



<p>Take <strong>care putting </strong>the class into the correctly <strong>named folder</strong> <strong>and </strong>watch the <strong>namespace</strong>!</p>



<p><strong>Create </strong>a <strong>folder </strong>called &#8222;<strong>Models</strong>&#8220; and <strong>add</strong> the following <strong>class inside</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Namespace Models

    Public Class Customer

        Public Property FirstName As String

        Public Property LastName As String

        Public Property Company As String

        Sub New(firstName As String, lastName As String, company As String)
            Me.FirstName = firstName
            Me.LastName = lastName
            Me.Company = company
        End Sub

    End Class

End Namespace
</pre>



<h3 class="wp-block-heading" id="creating-the-user-interface-for-the-vb-net-datagridview-filter-example">Creating the user interface for the VB NET DataGridView filter example</h3>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-user-interface.jpg"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/02/VB-NET-DataGridView-filter-user-interface.jpg" alt="Creating the user interface" class="wp-image-9151" title="Creating the user interface"/></a><figcaption class="wp-element-caption">Creating the user interface</figcaption></figure>



<p><strong>In </strong>this <strong>last step</strong> of the first example, we will actually <strong>work on <a href="https://en.wikipedia.org/wiki/Graphical_user_interface" target="_blank" rel="noreferrer noopener">the graphical user interface</a></strong> (GUI) part.</p>



<p>As <strong>this </strong>is a <strong>DataGridView example</strong> (so no WPF involved), we will <strong>use a</strong> good old <strong>Windows Forms Project</strong> (Winforms project).</p>



<p><strong>If you </strong>have <strong>missed </strong>the example preview, you can <strong>scroll back to</strong> the above <strong>section <a href="#application-preview">here</a></strong>.</p>



<h4 class="wp-block-heading" id="needed-controls">Needed controls</h4>



<p>So in order <strong>to create </strong>our example <strong>user interface </strong>we <strong>need </strong>the following controls:</p>



<ul class="wp-block-list">
<li>A <strong>form</strong> with set StartPosition, Text and size</li>



<li>One <strong>TableLayoutPanel </strong>(as we want dynamic resizing)</li>



<li><strong>Groupboxes </strong>(2) for the main areas</li>



<li>One <strong>FlowLayoutPanel</strong> for arranging the search inputs</li>



<li>a <strong>Textbox </strong>for searching by text input</li>



<li><strong>2 buttons </strong>(searching and resetting the search)</li>



<li>The last control is the <strong>DataGridView</strong> itself</li>
</ul>



<p><strong>Surely </strong>you can <strong>add or remove</strong> things <strong>on </strong>your personal <strong>needs</strong>..</p>



<h3 class="wp-block-heading" id="the-code-vb-net-datagridview-filter-example-1">The Code – VB NET DataGridView filter example 1</h3>



<p>Now, <strong>inside </strong>our <strong>code</strong>, we will start by <strong>importing </strong>all <strong>necessary namespaces</strong>.</p>



<p>I <strong>called my example</strong> project &#8222;<strong>VBDataGridViewFilterExample</strong>&#8222;, so <strong>make sure to adjust</strong> that to your project name if needed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Imports System.ComponentModel
Imports VBDataGridViewFilterExample.Models
Imports VBDataGridViewFilterExample.Utils</pre>



<h4 class="wp-block-heading" id="the-forms-properties">The forms properties</h4>



<p><strong>Then </strong>we will need to <strong>define 3 properties</strong> <strong>inside </strong>our &#8222;<strong>Form1</strong>&#8220; class (or however you&#8217;ve called it).</p>



<p>The <strong>first property</strong> called &#8222;<strong>Customers</strong>&#8220; is the <strong>storage for </strong>our <strong>customer </strong>instances.</p>



<p><strong>As </strong>I have <strong>mentioned above </strong>you should <strong>go for </strong>something like <strong>dependency injection</strong>, etc.</p>



<p>In <strong>this case</strong> it will be <strong>enough </strong>working <strong>like this</strong>, as I don&#8217;t want to make it too difficult anyways.</p>



<p>The next property &#8222;<strong>FilteredCustomers</strong>&#8220; <strong>will be</strong> the actual (potentially filtered) <strong>customers </strong>list, which is the <strong>datasource for </strong>our <strong>DataGridView</strong>.</p>



<p>Finally, <strong>the last property</strong> is some kind of <strong>user input</strong> field, where the <strong>user can</strong> enter some string to <strong>filter </strong>the <strong>customers </strong>by.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    Public Property Customers As List(Of Customer)

    Public Property FilteredCustomers As BindingList(Of Customer)

    Public Property SearchText As String</pre>



<h4 class="wp-block-heading" id="instantiating-the-form-the-constructor">Instantiating the form – The Constructor</h4>



<p><strong>Now </strong>it&#8217;s <strong>time to</strong> let the form actually come to reality by <strong>filling </strong>its <strong>constructor</strong> code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Sub New()
    InitializeComponent()
    Customers = New List(Of Customer)()
    FilteredCustomers = New BindingList(Of Customer)()
    SearchText = String.Empty
    tbSearch.DataBindings.Add(NameOf(Text), Me, NameOf(SearchText), False, DataSourceUpdateMode.OnPropertyChanged)
End Sub</pre>



<p>The <strong>first</strong> <strong>call </strong>is the &#8222;<strong>InitializeComponent</strong>&#8222;-function – <strong>like </strong>literally <strong>always</strong>.</p>



<p><strong>Next</strong>, we will <strong>instantiate both list </strong>objects called &#8222;Customers&#8220; and &#8222;FilteredCustomers&#8220;.</p>



<p><strong>Then </strong>we are going to <strong>initialize </strong>the &#8222;<strong>SearchText</strong>&#8220; property <strong>with </strong>an <strong>empty string</strong>, so it&#8217;s not &#8222;Nothing&#8220;.</p>



<h4 class="wp-block-heading" id="the-forms-load-eventhandler">The forms Load-EventHandler</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    tbSearch.DataBindings.Add(NameOf(Text), Me, NameOf(SearchText), False, DataSourceUpdateMode.OnPropertyChanged)
    LoadTestCustomers()
    dgvCustomers.DataSource = FilteredCustomers
    SearchCustomers()
End Sub</pre>



<p><strong>Inside </strong>the forms <strong>load eventhandler</strong>, theres also some work to do like <strong>configuring </strong>the <strong>bindings</strong>, etc.</p>



<p>So let&#8217;s <strong>start </strong>by <strong>binding </strong>the &#8222;<strong>SearchText</strong>&#8222;-property <strong>to </strong>our <strong>corresponding textboxes</strong> &#8222;Text&#8220;-property.</p>



<p>We are <strong>using a nice operator</strong> called &#8222;<strong><a href="https://docs.microsoft.com/de-de/dotnet/visual-basic/language-reference/operators/nameof" target="_blank" rel="noreferrer noopener">NameOf</a></strong>&#8222;, as this <strong>can help with later naming conflicts</strong>.</p>



<p><strong>If </strong>you would be <strong>calling</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tbSearch.DataBindings.Add(Text, Me, "SearchText", False, DataSourceUpdateMode.OnPropertyChanged)</pre>



<p><strong>and change </strong>the &#8222;SearchText&#8220;-<strong>property </strong>to a different name later on, you could run into problems.</p>



<p><strong>Changing </strong>&#8222;SearchText&#8220; <strong>to </strong>like &#8222;<strong>Search</strong>&#8222;, <strong>would </strong>lead the binding above to <strong>fail</strong>, if you don&#8217;t apply the change there as well.</p>



<p>But <strong>changing when using </strong>the &#8222;<strong>NameOf</strong>&#8222;-operator <strong>will </strong>instantly <strong>notify you </strong>about this.</p>



<p>I <strong>will talk about </strong>that &#8222;<strong>DataSourceUpdateMode</strong>&#8222;-part in a few moments, so be patient.</p>



<p><strong>Then </strong>we will <strong>continue </strong>by <strong>loading </strong>some <strong>customer test data</strong> into our backing storage list.</p>



<p>You <strong>will see </strong>the <strong>implementation </strong>for that method in some seconds, <strong>too</strong>!</p>



<p><strong>After that</strong>, we&#8217;re <strong>setting </strong>the <strong>DataGridViews DataSource </strong>property, to our &#8222;<strong>FilteredCustomers</strong>&#8220; BindingList.</p>



<p>In the <strong>last step</strong> <strong>of </strong>the <strong>load </strong>eventhandler, we will <strong>trigger</strong> a <strong>simulated search</strong>, to <strong>make </strong>some <strong>data appear </strong>at the start.</p>



<h4 class="wp-block-heading" id="the-loadtestcustomers-method">The LoadTestCustomers method</h4>



<p>This method will <strong>load some test customers</strong> <strong>into </strong>our basic storage <strong>list</strong>.</p>



<p>So nothing big is happening here, except <strong>creating 3 customers</strong> and adding them to the list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub LoadTestCustomers()
    Customers.Add(New Customer("John", "Doe", "JD Company"))
    Customers.Add(New Customer("Jane", "Doe", "JANE Ltd."))
    Customers.Add(New Customer("Maximillion", "Pegasus", "Industrial Illusions"))
End Sub</pre>



<h4 class="wp-block-heading" id="searchcustomers-method-definition">SearchCustomers method definition</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub SearchCustomers()
    If FilteredCustomers.Count > 0 Then
        FilteredCustomers.Clear()
    End If
    Dim searchResults = Customers.Where(AddressOf FilterCustomers)
    FilteredCustomers.AddRange(searchResults)
End Sub</pre>



<p>The &#8222;<strong>SearchCustomers</strong>&#8220; method will <strong>do</strong> the <strong>searchy work</strong> and <strong>add </strong>the <strong>results </strong>to our bound result list.</p>



<p><strong>As </strong>you may have already <strong>guessed</strong>, we <strong>will need </strong>that defined <strong>extension method </strong>from above.</p>



<p><strong>First </strong>it will <strong>clear out </strong>already <strong>existing customers </strong>(if there are any), so that we are <strong>starting </strong>in a <strong>clean </strong>way.</p>



<p>Then it&#8217;s using the <strong><a href="https://de.wikipedia.org/wiki/LINQ" target="_blank" rel="noreferrer noopener">LINQ</a></strong> helper method called &#8222;<a href="https://docs.microsoft.com/de-de/dotnet/api/system.linq.enumerable.where" target="_blank" rel="noreferrer noopener"><strong>Where</strong></a>&#8220; to apply our <strong>defined filtering function</strong> coming in a second.</p>



<p><strong>After </strong>we <strong>got </strong>our <strong>results</strong>, we can <strong>add them </strong>by the defined &#8222;<strong>AddRange</strong>&#8220; method <strong>from </strong>the <strong>top </strong>of this post.</p>



<h4 class="wp-block-heading" id="performing-the-filtering-by-filtercustomers-method">Performing the filtering by FilterCustomers method</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Function FilterCustomers(customer As Customer) As Boolean
    Dim searchText = Me.SearchText.ToLower()
    Dim company = customer.Company.ToLower()
    Dim firstName = customer.FirstName.ToLower()
    Dim lastName = customer.LastName.ToLower()
    Return company.Contains(searchText) OrElse
        firstName.Contains(searchText) OrElse
        lastName.Contains(searchText)
End Function</pre>



<p><strong>Now </strong>it&#8217;s time to <strong>define </strong>the <strong>predicate function </strong>for doing the actual filter work.</p>



<p>A <strong>customer does match</strong> our filter criteria, <strong>if </strong>the <strong>value </strong>of the &#8222;SearchText&#8220; property (lowered) <strong>is contained </strong>in:</p>



<ul class="wp-block-list">
<li>either, the <strong>company</strong></li>



<li>the <strong>first name</strong></li>



<li>or the <strong>last name</strong></li>
</ul>



<p><strong>Keep an eye on</strong> that &#8222;<strong><a href="https://docs.microsoft.com/de-de/dotnet/visual-basic/language-reference/operators/orelse-operator" target="_blank" rel="noreferrer noopener">OrElse</a></strong>&#8220; operator, as it&#8217;s <strong>enough if</strong> just <strong>one </strong>of this boolean expressions <strong>match</strong>.</p>



<p>So by just <strong>using </strong>&#8222;<strong>Or</strong>&#8220; it <strong>would</strong> still <strong>check all 3 expressions </strong>– which is <strong>inefficient</strong>!</p>



<h4 class="wp-block-heading" id="reacting-to-user-pressing-enter-a-ui-ux-thingy">Reacting to user pressing Enter – a UI/UX thingy</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub tbSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearch.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.Handled = True
        ' disable DING sound
        e.SuppressKeyPress = True
        SearchCustomers()
    End If
End Sub</pre>



<p>One <strong>basic functionality </strong>when <strong>creating </strong>some <strong>filtering mechanism </strong>should be to <strong>trigger </strong>the <strong>search by </strong>pressing a <strong>hotkey</strong>.</p>



<p><strong>If </strong>the <strong>user presses </strong>the &#8222;<strong>Enter</strong>&#8220; key inside the textbox, we <strong>will </strong>react by <strong>triggering </strong>the <strong>search</strong>.</p>



<p>But <strong>before </strong>finally <strong>triggering </strong>that <strong>search</strong>, we are setting the &#8222;<a href="https://docs.microsoft.com/de-de/dotnet/api/system.windows.forms.keypresseventargs.handled?view=windowsdesktop-6.0" target="_blank" rel="noreferrer noopener"><strong>Handled</strong></a>&#8220; event <strong>argument property</strong>.</p>



<p>We are <strong>also setting </strong>the &#8222;<strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keyeventargs.suppresskeypress?view=windowsdesktop-6.0" target="_blank" rel="noreferrer noopener">SuppressKeyPress</a></strong>&#8220; property, to avoid that annoying windows sided &#8222;DING&#8220; sound.</p>



<p>Let&#8217;s <strong>talk about</strong> that &#8222;<strong>DataSourceUpdateMode</strong>&#8220; thing I&#8217;ve mentioned a few moments ago.</p>



<p>This thing <strong>will configure </strong>the &#8222;<strong>SearchProperty</strong>&#8220; actually <strong>getting changed live</strong>.</p>



<p>If we would <strong>not be using that</strong>, you <strong>could trigger </strong>the search by pressing enter, <strong>but </strong>the <strong>actual text wouldn&#8217;t be used</strong>.</p>



<p>This <strong>happens</strong>, <strong>because </strong>the input <strong>text </strong>of the textbox <strong>only gets &#8222;forwarded&#8220;</strong> to our &#8222;SearchText&#8220; <strong>after leaving </strong>the <strong>textbox</strong>!</p>



<h4 class="wp-block-heading" id="the-button-event-handlers">The button event handlers</h4>



<p>So <strong>at the end</strong> of the first codes example, theres just one (or two things) left.</p>



<p>I&#8217;m <strong>talking about </strong>these two <strong>buttons </strong>whose click events need to be handled.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub btnResetSearch_Click(sender As Object, e As EventArgs) Handles btnResetSearch.Click
    tbSearch.Clear()
    SearchCustomers()
End Sub

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    SearchCustomers()
End Sub</pre>



<p>We are making sure, to <strong>reset </strong>the <strong>search and showing all customers </strong>when pressing the reset button.</p>



<p><strong>Then </strong>we are <strong>handling </strong>the <strong>normal search </strong>button click by <strong>triggering </strong>the <strong>search </strong>process.</p>



<h2 class="wp-block-heading" id="conclusion">Conclusion</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/02/Conclusion.jpg"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/02/Conclusion.jpg" alt="Creating a VB NET DataGridView filter functionality - conclusion" class="wp-image-8867" title="Creating a VB NET DataGridView filter functionality - conclusion"/></a><figcaption class="wp-element-caption">Creating a VB NET DataGridView filter functionality &#8211; conclusion</figcaption></figure>



<p>So <strong>now </strong>that we&#8217;ve <strong>come to the end</strong> of todays blog post, let&#8217;s <strong>do a</strong> quick <strong>recap</strong>.</p>



<p><strong>When </strong>it comes to <strong>displaying data in a tabular style</strong>, you are almost <strong>guaranteed </strong>to stumble upon <strong>DataGridViews</strong>.</p>



<p>But – like as usual – in the daily life of being a programmer, you <strong>will face more requirements</strong>.</p>



<p>So even if you managed to <strong>display</strong> <strong>data inside </strong>a <strong>DataGridView</strong>, you will get <strong>more requests </strong>like <strong>filtering</strong>, <strong>sorting </strong>and <strong>more</strong>.</p>



<p>In todays post I <strong>showed you </strong>one possible way of <strong>filtering data</strong> inside that tabular standard control.</p>



<p><strong>Next to </strong>that already <strong>existing method </strong>showed above, I think I <strong>will update this post</strong> in the future to show more.</p>



<h2 class="wp-block-heading" id="downloads">Downloads</h2>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://bit.ly/vbnet-datagridview-filter-download-en" target="_blank" rel="noreferrer noopener">VBDataGridViewFilterExample.zip</a></div>
</div>



<h2 class="wp-block-heading" id="related-posts">Related posts</h2>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/vb-net-removing-items-from-listboxes/" target="_blank" rel="noreferrer noopener">Removing Items from ListBoxes in VB NET</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/hacking-a-net-application/" target="_blank" rel="noreferrer noopener">Hacking a VB NET Application – or avoid getting hacked</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/creating-a-vb-net-datagridview-filter-functionality/">How to create a VB NET DataGridView filter functionality in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/creating-a-vb-net-datagridview-filter-functionality/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Eigener virtueller Mini-Desktop</title>
		<link>https://robbelroot.de/blog/eigener-virtueller-mini-desktop/</link>
					<comments>https://robbelroot.de/blog/eigener-virtueller-mini-desktop/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Thu, 11 Feb 2016 20:41:11 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET Problemlösungen]]></category>
		<category><![CDATA[desktop]]></category>
		<category><![CDATA[eigener]]></category>
		<category><![CDATA[mini]]></category>
		<category><![CDATA[monitor]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[virtual]]></category>
		<category><![CDATA[virtueller]]></category>
		<category><![CDATA[visual basic]]></category>
		<guid isPermaLink="false">http://robbelroot.de/?p=924</guid>

					<description><![CDATA[<p>Auf YouTube ansehen Code Download</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/eigener-virtueller-mini-desktop/">Eigener virtueller Mini-Desktop</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async=""></script><!-- robbelroot.de pre content --><ins class="adsbygoogle" style="display: inline-block; width: 468px; height: 60px;" data-ad-client="ca-pub-3635281460831831" data-ad-slot="4378945418"></ins><script>// <![CDATA[
(adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;</script></p>
<p style="margin-bottom:0;">
<a class="fasc-button fasc-size-medium fasc-type-glossy fasc-rounded-medium fasc-ico-before dashicons-format-video" style="background-color: #ff0000; color: #ffffff;" href="https://www.youtube.com/watch?v=j7qbJbZfTDw" target="_blank" data-fasc-style="background-color:#ff0000;color:#ffffff;">Auf YouTube ansehen</a> <a class="fasc-button fasc-size-medium fasc-type-glossy fasc-rounded-medium fasc-ico-before dashicons-download" style="background-color: #339e48; color: #ffffff;" href="https://adf.ly/1LiCDC" target="_blank" data-fasc-style="background-color:#339e48;color:#ffffff;">Code Download</a>
</p>
<p><iframe loading="lazy" width="560" height="315" src="https://www.youtube.com/embed/j7qbJbZfTDw" frameborder="0" allowfullscreen></iframe></p>
<p><script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async=""></script><!-- robbelroot.de pre content --><ins class="adsbygoogle" style="display: inline-block; width: 468px; height: 60px;" data-ad-client="ca-pub-3635281460831831" data-ad-slot="4378945418"></ins><script>// <![CDATA[
(adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;</script></p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/eigener-virtueller-mini-desktop/">Eigener virtueller Mini-Desktop</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/eigener-virtueller-mini-desktop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
