简体   繁体   中英

To insert datepicker date to sql server

I want to insert a date from datepicker to sql server.The table is as below :

Create table testDate
(
EventStart date,
EventEnd date
)

Create proc sptestdate
@EventStart date,
@EventEnd date
as
begin
Insert into testDate(EventStart,EventEnd) values(@EventStart,@EventEnd)
end

and the datepicker is as below :

 <script>
    $(function () {
        $(".datepicker").datepicker({
            dateFormat: "dd/mm/yy"
        });
    });
</script>

I do this using the below code-behind:

    protected void Button1_Click(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("sptestdate", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EventStart", SqlDbType.DateTime).Value = txtEventStart.Value;
        cmd.Parameters.AddWithValue("@EventEnd", SqlDbType.DateTime).Value = txtEventEnd.Value;
        cmd.ExecuteNonQuery();
    }
}

However, it throws an error

  "Error converting data type nvarchar to date."

You need to pass DateTime object to your DB rather than passing a String (Textbox.Text returns String), you can use DateTime.Parse :-

DateTime.Parse(txtEventStart.Value);
DateTime.Parse(txtEventEnd.Value);

You can also use DateTime.ParseExact method.

DateTime result;
result = DateTime.ParseExact("your_date", format, provider);

This will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM