0
我嘗試了不同的格式,但仍然給出此例外。字符串在有效日期時間內未被識別
我想使用select命令在gridview中顯示數據表。
我在SQL Server表中使用Expense_Date列作爲日期數據類型。
我的代碼在這裏。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class ConsolidateByMonth : System.Web.UI.Page
{
double grdTotal = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnShowExpenses_Click(object sender, EventArgs e)
{
string month = DropDownList1.Text;
string NoOfMonth="";
string days="";
switch(month){
case "January":
NoOfMonth = "01";
days = "31";
break;
case "Febuary":
NoOfMonth = "02";
days = "28";
break;
case "March":
NoOfMonth = "03";
days = "31";
break;
case "April":
NoOfMonth = "04";
days = "30";
break;
case "May":
NoOfMonth = "05";
days = "31";
break;
case "June":
NoOfMonth = "06";
days = "30";
break;
case "July":
NoOfMonth = "07";
days = "31";
break;
case "August":
NoOfMonth = "08";
days = "31";
break;
case "September":
NoOfMonth = "09";
days = "30";
break;
case "October":
NoOfMonth = "10";
days = "31";
break;
case "November":
NoOfMonth = "11";
days = "30";
break;
case "December":
NoOfMonth = "12";
days = "31";
break;
}
string str1 = (NoOfMonth + "01" + DropDownList2.Text).ToString(); //04012014
string str2 = (NoOfMonth + days + DropDownList2.Text).ToString();
DateTime date1 = DateTime.ParseExact(str1, "yyyy-MM-dd", null);
DateTime date2 = DateTime.ParseExact(str2, "yyyy-MM-dd", null);
string con_string = "@data source=10.10.10.5; initial catalog= testAzhar; user=xx; password=xxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qry = "Select Expense_Category, Expense_Description, Amount from CompanyExpenses3 where Expense_Date>=" + date1 + "and <=" + date2;
SqlCommand cmd = new SqlCommand(qry, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
con.Close();
}
請糾正我。
始終使用SQL參數(...'其中EXPENSE_DATE> = @ Expense_Date' ...)而不是字符串連接來防止SQL注入和本地化問題。 –
您應該使用DateTime.DaysInMonth(int,int),以便您的代碼在閏年中正常工作,而不是硬編碼的switch語句。 –