我得到一个FormatException,消息“String未被识别为有效的DateTime”。在以下代码行中:
SqlCommand scmd1 = new SqlCommand("select count(*) Kount from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);
请说明出了什么问题。
感谢。
答案 0 :(得分:2)
您指定了错误的解析格式:dd-MMM-yyyy
您的文本框采用dd-MM-yyyy
格式。
更改格式,传递给ParseExact
,它应该有效:
SqlCommand scmd1 = new SqlCommand("select count(*) Kount from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);
通常,最好停止连接字符串以构建SQL查询,并开始使用SQL参数。
SqlCommand scmd1 = new SqlCommand("select count(*) Kount from chequerequests1 where requestdate between @dateStart and @dateEnd group by chequebookstatus", sc);
DateTime dtStart = DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).StartOfDay();
DateTime dtEnd = DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).EndOfDay();
scmd1.Parameters.AddWithValue("dateStart", dtStart);
scmd1.Parameters.AddWithValue("dateEnd", dtEnd);