Serenade
Serenade

Reputation: 50

Filter Date Range in Datagridview didn't work if months are different

I know this is an old problem but I still confuse a little bit, please show me how.

I loaded a datatable with conditions in datagridview like the code below, thing is, It worked well when FromDate and ToDate are the SAME MONTH. Different month makes the datagridview empty.

FromDate and ToDate are selected in calendar into the 2 textbox.

private void LoadWorkRequestSearch()
{
    DateTime datefrom = Convert.ToDateTime(textdatefrom.Text.Trim());
    DateTime dateto = Convert.ToDateTime(textdateto.Text.Trim());

    string sql = "";
    sql = "Select DateCreated, ri.RequestID, RequesterID, RequestStatus, RequestDetail, SentTo, EstimateCompleteDate, ru.StartedDate, ru.ProcessTime From [RequestInfo] ri ";
    sql = sql + " LEFT JOIN [StatusRequest] sr ON sr.RequestStatusID = ri.Status";
    sql = sql + " LEFT JOIN [RequestUsers] ru ON ru.RequestID = ri.RequestID ";
    sql = sql + " Where DateCreated between '" + datefrom.ToShortDateString() + "' and '" + dateto.ToShortDateString() + "'";

    _dtworkrequestsearch = _cls_DB.QueryDataTable(sql);
    G1.DataSource = _dtworkrequestsearch;

}

I tried everything I searched but it didn't work the way I want, please help.

Thank you,

Upvotes: 0

Views: 383

Answers (1)

Jeremy Thompson
Jeremy Thompson

Reputation: 65544

Use a Calendar Control and enforce a date format.

The conversion to date from TextBox is the likely problem, eg dd/MM into MM/dd

Edit:

You're using a varchar(10) field for dates. That doesn't allow SQL BETWEENS because it's a text field not numeric/date based, so it performs an alphanumeric search.

Use a SmallDateTime column for DateCreated to get the desired results.

Upvotes: 1

Related Questions