I’m trying to filter a deadline column in a datagridview by 2 datetimepickers – startDate and endDate.
datagridview is TaskTable2,
datetimepicker1 is startSchedule,
datetimepicker2 is endSchedule and
deadline in datagridview is deadlineRow
So far I have got the following code which is successfully making the rows invisible which are not between the selected start and end date.
private void scheduleButton_Click(object sender, EventArgs e)
{
DateTime startSchedule = startDate.Value.Date;
DateTime endSchedule = endDate.Value.Date;
if (startSchedule <= endSchedule)// runs foreach loop if startdate and enddate are valid
{
foreach (DataGridViewRow dr in TaskTable2.Rows)// loops through rows of datagridview
{
string deadline = dr.Cells["Deadline"].Value.ToString(); // gets deadline values
DateTime deadlineRow = Convert.ToDateTime(deadline); // converts deadline string to datetime and stores in deadlineRow variable
if (startSchedule <= deadlineRow && deadlineRow <= endSchedule) // filters deadlines that are => startDate and <= endDate
{
dr.Visible = true; // display filtered rows here.
}
else
{
dr.Visible = false; // hide rows that are not beteen start and end date.
}
}
}
else
{
MessageBox.Show("Please ensure Start Date is set before End Date."); // ensures user selects an end date after the start date.
}
}
However, I have a few existing problems:
- The application crashes and I get the following error when I select a date range that will display no tasks:
‘Row associated with the currency manager’s position cannot be made invisible’
- I have a print button that is supposed to print the filtered results.
However, it is printing all data stored in the datagridview, even if some rows are visible=false from pressing the schedule button so I’m guessing I need to use a different approach to remove the rows rather than hide them.
The datagridview is bound to an XML file so data can be removed from the datagridview for filtering and printing aslong as they remain in the XML file.
Any help would be greatly appreciated!
Thankyou
I would use the
Filterproperty on thebindingsourcefor thedatagridview. TheFilterproperty allows you to view a subset of the DataSource.Example from MSDN:
I use this type of
Filterto show data based on account. For an account, I have a textbox when the user places the account number and I use theTextChangedEvent to apply the filter. Then I have a button that is used to remove the Filter from the binding source.If you want to filter by date you can following instructions in this SO question:
BindingSource Filter by date
Using the filter on a date that is not present should not crash the app, it will just display nothing.