I have a DataTable dt with two columns FromDate and ToDate. I have two textboxes where I am entering the dates blackOutFromDate and blackOutToDate. Say, I have 7 rows inside my DataTable dt:
From Date To Date
8/21/2012 To 8/22/2012
8/23/2012 To 8/24/2012
8/25/2012 To 8/25/2012
8/5/2012 To 8/6/2012
8/26/2012 To 8/27/2012
8/1/2012 To 8/2/2012
8/3/2012 To 8/3/2012
If the value that I enter inside my text boxes CheckInDate and CheckOutDate is between any matching date range of DataTable dt, it should return the count of the noumber of rows having such match.
I am doing
foundRows = _blackOutTable.Select
(
"(FromDate <='" +
blackOutFromDate.ToShortDateString() + "' AND ToDate >= '" +
blackOutFromDate.ToShortDateString() + "')"
+ "OR (FromDate <='" +
blackOutToDate.ToShortDateString() + "' AND ToDate >='" +
blackOutToDate.ToShortDateString() + "')"
+ "OR (FromDate >='" +
blackOutFromDate.ToShortDateString() + "' AND FromDate <='" +
blackOutToDate.ToShortDateString() + "')"
+ "OR (ToDate >= '" +
blackOutFromDate.ToShortDateString() + "' AND ToDate <='" +
blackOutToDate.ToShortDateString() + "')"
);
if (foundRows.Length == 0)
{
}
EDIT :
I am storing the DateFrom and DateTo filed inside SQl Server as
CAST(MONTH(date1) AS VARCHAR(2)) + '/' + CAST(DAY(date1) AS VARCHAR(2)) + '/' +
CAST(YEAR(date1) AS VARCHAR(4)) [fromdate],
CAST(MONTH(date2) AS VARCHAR(2)) + '/' + CAST(DAY(date2) AS
VARCHAR(2)) + '/' + CAST(YEAR(date2) AS VARCHAR(4)) [todate]
blackOutFromDate and blackOutFromDate are of DateTime types.
But it’s not returning the correct values. There is some problem with the select expression. What can I do to fix this?
This is theDataTable.SelectsyntaxforDateTimes:So you need to use
String.Formatto put your date variable into that string.Edit: Since your datetimes are converted to varchar and you cannot change that, you need to parse them back to datetime. I would recommend to use
Linq-To-DataSet:You can use
foreachto enumerate all rows or useCopyToDataTableto create a newDataTablefrom the filteredDataRows.