Casting DataGridview / BindingSource / Filter ?

Posted on 2016-09-16
Last Modified: 2016-09-19
I have a DataGridView that is bound to a BindingSource, and I have a filter set. I need to cast this data to a DataTable. But when I do it it ignores the filter. How can I cast it and have it give me only the data that matches the filter?

Here is how I am casting it now:
dt = CType(DirectCast(Me.DGVSelectedBooks.DataSource, BindingSource).DataSource, DataTable)
Question by:Jess31
1 Comment
LVL 33

Accepted Solution

it_saige earned 500 total points
ID: 41802243
You want to use the List property of the BindingSource to retrieve the filtered list; e.g. -
dt = CType(CType(DGVSelectedBooks.DataSource, BindingSource).List, DataView).ToTable()

Open in new window

Proof of concept:

Form1.vb -
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Public Class Form1

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		BindingSource1.DataSource = (From i In Enumerable.Range(0, 20) Select New With {.ID = i, .FirstName = String.Format("{0}{1}", If(i Mod 5 = 0, "Paul", If(i Mod 4 = 0, "Larry", If(i Mod 3 = 0, "Susan", If(i Mod 2 = 0, "Mary", "Peter")))), i), .LastName = String.Format("LastName{0}", i), .BirthDate = DateTime.Now.AddYears(-(9 * i)), .IsWorking = i Mod 2 = 0}).ConvertToDataTable()
		DataGridView1.DataSource = BindingSource1
	End Sub

	Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
		If TypeOf sender Is Button Then
			Dim btn = DirectCast(sender, Button)
			If btn.Equals(Button1) Then
					BindingSource1.Filter = TextBox1.Text
				Catch ex As Exception
					BindingSource1.Filter = ""
				End Try
			ElseIf btn.Equals(Button2) Then
				Dim child As Form = New Form() With {.AutoSize = True}
				Dim bnd As New BindingSource()
				bnd.DataSource = CType(CType(DataGridView1.DataSource, BindingSource).List, DataView).ToTable()
				Dim dgv As New DataGridView() With {.Dock = DockStyle.Fill}
				dgv.DataSource = bnd
			End If
		End If
	End Sub
End Class

Module Extensions
	<Extension()> _
	Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T)) As DataTable
		Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim table As DataTable = New DataTable()

		For i As Integer = 0 To properties.Count - 1
			Dim [property] As PropertyDescriptor = properties(i)
			If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
				table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
				table.Columns.Add([property].Name, [property].PropertyType)
			End If

		Dim values(properties.Count - 1) As Object
		For Each item As T In source
			For i As Integer = 0 To properties.Count - 1
				values(i) = properties(i).GetValue(item)

		Return table
	End Function
End Module

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
			If disposing AndAlso components IsNot Nothing Then
			End If
		End Try
	End Sub

	'Required by the Windows Form Designer
	Private components As System.ComponentModel.IContainer

	'NOTE: The following procedure is required by the Windows Form Designer
	'It can be modified using the Windows Form Designer.  
	'Do not modify it using the code editor.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.components = New System.ComponentModel.Container()
		Me.DataGridView1 = New System.Windows.Forms.DataGridView()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.Button1 = New System.Windows.Forms.Button()
		Me.BindingSource1 = New System.Windows.Forms.BindingSource(Me.components)
		Me.Button2 = New System.Windows.Forms.Button()
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
		CType(Me.BindingSource1, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.DataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill
		Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
		Me.DataGridView1.Location = New System.Drawing.Point(13, 13)
		Me.DataGridView1.Name = "DataGridView1"
		Me.DataGridView1.RowHeadersVisible = False
		Me.DataGridView1.Size = New System.Drawing.Size(468, 194)
		Me.DataGridView1.TabIndex = 0
		Me.TextBox1.Location = New System.Drawing.Point(13, 229)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(383, 20)
		Me.TextBox1.TabIndex = 1
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(13, 210)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(32, 13)
		Me.Label1.TabIndex = 2
		Me.Label1.Text = "Filter:"
		Me.Button1.Location = New System.Drawing.Point(402, 227)
		Me.Button1.Name = "Button1"
		Me.Button1.Size = New System.Drawing.Size(75, 23)
		Me.Button1.TabIndex = 3
		Me.Button1.Text = "Apply"
		Me.Button1.UseVisualStyleBackColor = True
		Me.Button2.Location = New System.Drawing.Point(13, 255)
		Me.Button2.Name = "Button2"
		Me.Button2.Size = New System.Drawing.Size(464, 23)
		Me.Button2.TabIndex = 4
		Me.Button2.Text = "Show Filtered DataTable"
		Me.Button2.UseVisualStyleBackColor = True
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(489, 286)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.BindingSource1, System.ComponentModel.ISupportInitialize).EndInit()

	End Sub
	Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents Button1 As System.Windows.Forms.Button
	Friend WithEvents BindingSource1 As System.Windows.Forms.BindingSource
	Friend WithEvents Button2 As System.Windows.Forms.Button

End Class

Open in new window

Produces the following output -

Initial load -Capture.JPGFiltered -Capture.JPGAfter pressing 'Show Filtered Data Table' -Capture.JPG

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now