I'm getting an issue when executing a reader to retrieve some DateTimes from a table.
First, I have one page transferring over some variables to another page:
//calStart.SelectedDate is a DateTime value
Response.Redirect("SpecialReports_Results.aspx?userListValues=" + userListValues + "&groupListValues=" + groupListValues + "&calSelected=" + calStart.SelectedDate);
Then, on the new page:
//To retrieve the values that were sent over
string userListValues = Request.QueryString["userListValues"];
string groupListValues = Request.QueryString["groupListValues"];
string dateSelected = Request.QueryString["calSelected"];
// SQL Server connection stuff + string argument
SqlCommand command2 = new SqlCommand();
command2.Connection = gconn;
String sql2 = "SELECT MAX([Day]) as TheDay FROM Days WHERE User_ID = @User_ID AND [Day] < '@dateSelected' AND NOT EXISTS (SELECT 1 FROM Days WHERE User_ID = @User_ID AND [DAY] >= '@dateSelected')";
command2.CommandText = sql2;
command2.Parameters.Add(new SqlParameter("@User_ID", ""));
command2.Parameters.Add(new SqlParameter("@dateSelected", dateSelected));
List<string> dates = new List<string>();
//userID is a List<string>
foreach (string str in userID)
{
command2.Parameters["@User_ID"].Value = str;
using (SqlDataReader reader = command2.ExecuteReader())
{
while (reader.Read()) //Getting error here: Conversion failed when converting datetime from character string.
{
if (reader.HasRows)
{
dates.Add(reader["Day"].ToString());
}
}
}
}
The table Days
is set up like so:
User_ID | Day
----------------------------------
10 | 2010-11-09 00:00:00.000
20 | 2015-12-06 00:00:00.000
30 | 2012-01-12 00:00:00.000
40 | 2013-07-23 00:00:00.000
The Day
column is of type DateTime
.
I have tried converting the string dateSelected
and the List<string>
dates to DateTime
by doing:
DateTime confirmedDate = DateTime.Parse(dateSelected);
List<DateTime> dates = new List<DateTime>()
But I get the same error.
Note: The SQL statement does work when executed in Microsoft's SQL Server Management Studio.