varchar数据类型到datetime数据类型错误的转换

时间:2019-04-03 10:40:36

标签: c# asp.net stored-procedures

将varchar数据类型转换为日期时间数据类型时出错,此语句在“ sda.Fill(dt);”中出现错误。

protected void btnSearch_Click(object sender, EventArgs e)
{
    // getData();
    // getDatas();`enter code here`
    string mainconn = ConfigurationManager.ConnectionStrings["PGAConnectionString"].ConnectionString;
    SqlConnection sqlconn = new SqlConnection(mainconn);

    //  string sqlquery = "  Select * from tbl_registration where registration_date between '" + txtfromDate.Text + "'and'" + txtToDate.Text + "'";
    //string sqlquery ="Select* from tbl_registration where registration_date between '" + txtfromDate.Text + "'and'" + txtToDate.Text + "'";
    //string sqlquery = "Select* from tbl_registration where registration_date between '2018/12/10' and '2018/12/13'";
    //string sqlquery = "  Select * from tbl_registration";
     SqlCommand sqlcomm = new SqlCommand("getuserdatewisereport", sqlconn);
    //SqlCommand sqlcomm = new SqlCommand(sqlquery , sqlconn);
    sqlcomm.CommandType = CommandType.StoredProcedure;
    sqlconn.Open();
    sqlcomm.Parameters.AddWithValue("@startdate", txtfromDate.Text);
    sqlcomm.Parameters.AddWithValue("@enddate", txtToDate.Text);

    SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
    DataTable dt = new DataTable();
    sda.Fill(dt);

    sqlcomm.ExecuteNonQuery();
    gridData.DataSource = dt;
    gridData.DataBind();
    sqlconn.Close();
}

enter image description here

1 个答案:

答案 0 :(得分:1)

在传递日期时间之前,应将其解析为DateTime变量,然后将其传递给存储过程。

DateTime startdate = DateTime.Parse(txtfromDate.Text);
DateTime enddate = DateTime.Parse(txtToDate.Text);

sqlcomm.Parameters.AddWithValue("@startdate", startdate);
sqlcomm.Parameters.AddWithValue("@enddate", enddate);