如何从日期到日期ASP.NET和SQL Server搜索gridview

时间:2018-02-21 10:26:39

标签: asp.net sql-server

这是我抛出错误的代码。我使用输入类型文本进行html编码。

using (SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=1GCAttendanceManagementSystem;Integrated Security=True"))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Attendances WHERE Date BETWEEN @From AND @To", con))
    {
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
           cmd.Parameters.Add("@From", SqlDbType.Date).Value = datepicker1.Text;
           cmd.Parameters.Add("@To", SqlDbType.Date).Value = datepicker2.Text;

           DataSet ds = new DataSet();
           da.Fill(ds);

           GridView1.DataSource = ds;
           GridView1.DataBind();
       }
   }
}

This is the screenshot of the error

1 个答案:

答案 0 :(得分:1)

您正在获取Text string并传递它。首先尝试将其转换为DateTime DateType,如:

   DateTime oDateFrom = Convert.ToDateTime(datepicker1.Text);
   DateTime oDateTo = Convert.ToDateTime(datepicker2.Text);

然后将它们传递给parameters

cmd.Parameters.Add("@From", SqlDbType.Date).Value = oDateFrom;
cmd.Parameters.Add("@To", SqlDbType.Date).Value = oDateTo;

希望有帮助和请,在您再次提出问题之前请阅读; How should i ask a good question?