我正在使用asp.net c#代码,以便使用sql查询和下拉列表填充Gridview。 场景是:
将char数据类型转换为datetime数据类型会导致日期时间值超出范围
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Condtion = "";
this.BindGrid(Condtion);
}
}
//Fill Grid View
private void BindGrid( String Condtion )
{
string strConnString = ConfigurationManager.ConnectionStrings["ICIRDATAConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
String Qsql = "Select * from WeeklyReportView " + Condtion + "";
using (SqlCommand cmd = new SqlCommand(Qsql))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
//Drop down List Selected Index Changed
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DateTime dt;
if(DropDownList1.SelectedValue!="1")
{
dt = DateTime.ParseExact(DropDownList1.SelectedValue, "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-GB"));
Condtion1 = "wr_week='" + dt + "'";
}
Condtion2 = "eng_name='" + DropDownList2.SelectedValue + "'";
if (DropDownList1.SelectedValue != "1" && DropDownList2.SelectedValue != "1")
{
Condtion = "Where " + Condtion1 + " and " + Condtion2;
}
else if (DropDownList2.SelectedValue != "1" && DropDownList1.SelectedValue == "1")
{
Condtion = "Where " + Condtion2;
}
else if (DropDownList2.SelectedValue == "1" && DropDownList1.SelectedValue != "1")
{
Condtion = "Where " + Condtion1;
}
else
{
Condtion = "";
}
this.BindGrid(Condtion);
}
任何人都可以提供帮助吗?
答案 0 :(得分:0)
尝试此查询
select * from table where date='"+DropDownList1.SelectedItem.ToString()+"';
答案 1 :(得分:0)
试试这种方式
dt = DateTime.Parse(DropDownList1.SelectedValue,System.Globalization.CultureInfo.InvariantCulture);
string ouputDate = dt.ToUniversalTime().ToString("dd/MM/yyyy hh:mm:ss",System.Globalization.CultureInfo.InvariantCulture);
Condtion1 = "wr_week='" + ouputDate + "'";
答案 2 :(得分:0)
您要么传递日期,要么传递参数类型的日期时间。您不能将datetime对象放入字符串并将其发送到sql server。
更改此行:
dt = DateTime.ParseExact(DropDownList1.SelectedValue, "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-GB"));
Condtion1 = "wr_week='" + dt + "'";
要:
dt = DateTime.ParseExact(DropDownList1.SelectedValue, "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-GB"));
var datestring = dt.ToString("yyyy-MM-dd HH:mm:ss");
Condtion1 = "wr_week=convert(datetime, '"+ datestring +"', 121)";
答案 3 :(得分:0)
谢谢大家的贡献,我找到了解决方案,实际上我的机器上安装的SQL Server和安装在服务器机器上的SQL Server之间存在不兼容问题,问题是我的sql server有“dd” / MM / yyyy hh:mm:ss“作为日期格式,但服务器机器sql server有”yyyy-MM-dd hh:mm:ss.mmm“。 再次感谢。