Bindingsource filter is not working right

264 Views Asked by At

I need to filter ADGV between dates with datepicker1 and datepicker2, but my code only filter Day, no matter the month or year it filters between DAYS only. I tried to messagebox my var values : string with 3/1/2018 datetry is 01.03.2018 datepicker1 is 01.05.2019 datepicker2 is 27.05.2019 and filter looks like this Data >= '01.05.2019' AND Data < '27.05.2019' and i don't get first day in the list, list starts from day 2 (3/2/2018). I tried in the csv file to change format to 3.1.2018 but that didin't help.

P.S. I'm taking my data from .csv file, no database is used so i can't use sql query.

I tried to google it, found similar problems and solutions but none of it was exact like me and i can't adopt it to my code, because i'm not good with programming but i need to make this "filter data" program.

string line;
 while ((line = sr.ReadLine()) != null)
 {
 if (!(line.Contains("#")))
{
 string[] columns = line.Split(';');
string datynski = columns[0];
DateTime dateTry = DateTime.ParseExact(datynski,"M/d/yyyy",CultureInfo.InvariantCulture);
datatable1.Rows.Add(dateTry.ToShortDateString(), columns[1], columns[2], columns[3]);
}
bindingsource1.DataSource = datatable1;
bindingsource1.Filter = "Data >= '" + dateTimePicker1.Value.Date + "' and Data <= '" + dateTimePicker2.Value.Date + "'";
adgv.DataSource = bindingsource1;
}
2

There are 2 best solutions below

3
janavarro On

Transforming to datetime should be easy.

The filter could be like this (using LinQ):

public static List<DateTime> FilterDatesBetween(List<DateTime> dates, 
DateTime start, DateTime end)
{
    return dates.Where(date => IsDateInPeriod(date, start, end)).
                        OrderBy(date => date).ToList();
}

public static bool IsDateInPeriod(DateTime date, DateTime start, DateTime end)
{
    return (date > start && date < end);
}
0
Yair I On

try this:

string line;
while ((line = sr.ReadLine()) != null) {
 if (!(line.Contains("#"))) {
    string[] columns = line.Split(';');

    //this two line are to make sure we have date on the field if you sure its date you can just use this: DateTime.Parse(columns[0]).ToString("yyyy-MM-dd");
    DateTime dateTry = new DateTime();
    DateTime.TryParse(columns[0], out dateTry);

    datatable1.Rows.Add(dateTry.ToString("yyyy-MM-dd"), columns[1], columns[2], columns[3]);    
}                   
bindingsource1.DataSource = datatable1;
adgv.DataSource = bindingsource1;