How to check if the date comes in between the particular date range in ASP.NET

In my requirement, I am inserting the residential history details into the GridView... It also contains FromDate & ToDate... So for first row, there is no condition.. On inserting second row, the FromDate & ToDate should not clash with my first row date range.. Is there any idea to avoid that????

FromDate ToDate Place

12/10/2012 12/05/2013 XXXXX

12/05/2004 12/09/2014 YYYYY

Second row should not be Allowed.. Bcoz in 2004 - 2014, already 2012 - 2013 time period is already mentioned.. So, this thing should not be added into the GridView

My Code:

protected bool ValidateResidenceDates(DateTime frmDate, DateTime toDate)
    {
        bool isValid = true;
        DataTable dt = (DataTable)Session["ResidenceNew"];

        if(dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DateTime dtFromDate = Convert.ToDateTime(dr["HKR_FromDate"], ci);
                    DateTime dtToDate = Convert.ToDateTime(dr["HKR_ToDate"], ci);

                    if (frmDate > dtFromDate && frmDate < dtToDate)
                    {
                        Com.MessageBox("From Date is Already Mentioned in the Residence History Date Range", UpdatePanel1);
                        SetFocus(txtResideFromDate);
                        isValid = false;
                        return isValid;
                    }
                    if (toDate > dtFromDate && toDate < dtToDate)
                    {
                        Com.MessageBox("To Date is Already Mentioned in the Residence History Date Range", UpdatePanel1);
                        SetFocus(txtResideToDate);
                        isValid = false;
                        return isValid;
                    }
                }
            }
        }
        return isValid;
    }

Upvotes: 0

Views: 1222

Answers (1)

Sandeep
Sandeep

Reputation: 1210

You also need to check following scenario:

1) frmDate >= dtFromDate && toDate <= dtToDate

Let say there is already entry for 2003-2015 then user can not add 2004-2014

2) frmDate <= dtFromDate && toDate >= dtToDate

this is the case which you have mentioned. already added for 2012-2013 then user can not add 2004-2014

Upvotes: 1

Related Questions