I want to filter datagridview between two datetimepicker without the involvement of a database. The datagridview has in-memory stored records. I'm using C# with .NET framework.
I have a DataGridView called "datagridview1", and 2 datetimepickers called "dateTimePickerFromDate" and "dateTimePickerToDate". So I need to search for the records in datagridview1, where the records are only between the 2 chosen dates, and I need to load the datagridview1. The date is based on the Transaction Date in the datagridview1.
CodePudding user response:
Here is an example using a DataTable with minimal data which loads a BindingSource needed for filtering. Two variables are used, replace them with your DateTimePicker controls.
Code in Button1 toggle the filter.
using System;
using System.Data;
using System.Windows.Forms;
namespace YourNameSpace
{
public partial class DemoForm : Form
{
private readonly BindingSource _bindingSource = new BindingSource();
public DemoForm()
{
InitializeComponent();
_bindingSource.DataSource = MockedData();
dataGridView1.DataSource = _bindingSource;
}
public DataTable MockedData()
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("TransactionDate", typeof(DateTime));
dt.Rows.Add(1, new DateTime(2022, 9, 3));
dt.Rows.Add(2, new DateTime(2022, 6, 3));
dt.Rows.Add(3, new DateTime(2022, 10, 1));
dt.Rows.Add(4, new DateTime(2022, 9, 11));
dt.Rows.Add(5, new DateTime(2022, 9, 12));
return dt;
}
private void button1_Click(object sender, EventArgs e)
{
// replace the two vars with DateTimePickers
var lowDate = new DateTime(2022, 9, 1);
var highDate = new DateTime(2022, 9, 12);
if (string.IsNullOrWhiteSpace(_bindingSource.Filter))
{
_bindingSource.Filter = $"TransactionDate >= '{lowDate}' AND TransactionDate <= '{highDate}'";
}
else
{
_bindingSource.Filter = "";
}
}
}
}