Link to home
Start Free TrialLog in
Avatar of dreinmann
dreinmannFlag for United States of America

asked on

Filter datagridview by range.

How do I filter a datagridview for a date range?
I have a table that I'm displaying in a datagridview.  I want to be able to click a button and ask the user to enter dates to filter the datagridview by.   One of the fields in the datagridview is obviously a date.  Once the two dates are entered, I want the datagridview to only show records from the 1st date, to the 2nd date.

ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Loop over the set of rows in the collection.
1. If you want to hide them, test the date for that row. If outside the range, set row.Visible to false.

2. If you want to remove them, start at the last row, and work your way to the first. If the date is outside the range, yourDataGridView.Rows.RemoveAt(currentIndex)

Jim
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
My apologies to TheLearnedOne for referencing you.  I have the utmost respect for you.  I just didn't
want it to appear as though I was duplicating your code, without showing what I was doing different.

Avatar of dreinmann

ASKER

dt.DefaultView keeps coming up with an error saying that it is readonly.  Readonly is fine with me, but the program won't allow it.
INTERESTING...  How do you end up with a ReadOnly DataGridView?

Try this alternate approach, it should work for your:

        'Set these to the dates entered by the user
        Dim startDate As Date = Today.Date
        Dim enddate As Date = DateAdd(DateInterval.Day, 2, Today.Date)

        'Assuming your column name in your table is "Date"
        Dim bs As New BindingSource()
        bs.DataSource = Me.DataGridView1.DataSource
        bs.Filter = "Date>=#" & startDate & "# AND Date<=#" & enddate & "#"
        Me.DataGridView1.DataSource = bs

This worked:
Dim dt As DataTable = ds.Tables("TimeOffRequests")
        dt.DefaultView.RowFilter = "StartDateTime >= #10/24/2007# AND StartDateTime <= #10/25/2007#"
        Me.dgvViewRequests.DataSource = dt.DefaultView

I was missing the .RowFilter at the end of dt.DefaultView.
The dates work as '10/24/2007' or as #10/24/2007#.

thanks all