Click here to Skip to main content
16,018,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day everyone..
I am trying to insert/save dropdownlist value to my database.
However, it always comes out with the error which "Conversion failed when converting date and/or time from character string..."

I had tried ways such as Convert.ToDateTime() and DateTime.Parse() in my codes but the error still occurs.

And yes.. the datatype for the "classStart" and "classEnd" are DATETIME.

Thanks in advance for the help.

What I have tried:

Here is my codes...
C#
protected void Page_Load(object sender, EventArgs e)
    {
        // Set the start time in dropdownlist timedd & timedd2
        DateTime StartTime = DateTime.MinValue.AddHours(8);
        // Set the end time in dropdownlist timedd & timedd2
        DateTime EndTime = DateTime.MinValue.AddDays(1);

        for (var i = StartTime; i <= EndTime; i = i.AddMinutes(30))
        {
            timedd.Items.Add(i.ToShortTimeString());
            timedd2.Items.Add(i.ToShortTimeString());
        }
}

protected void saveSchedule_Click(object sender, EventArgs e)
    {

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
        
        try
        {
            conn.Open();
            string addquery = "INSERT INTO [Schedule] ([className],[classStart],[classEnd],[classDes]) VALUES (@className, @classStart, @classEnd, @classDes)";
            SqlCommand cmd = new SqlCommand(addquery, conn);
            cmd.Parameters.AddWithValue("@className", className.Text); 
            cmd.Parameters.AddWithValue("@classStart", Convert.ToDateTime(timedd.SelectedItem.Value));
            cmd.Parameters.AddWithValue("@classEnd", Convert.ToDateTime(timedd2.SelectedItem.Value));
            cmd.Parameters.AddWithValue("@classDes", classdes.Text);
            
            int rs = cmd.ExecuteNonQuery();
            if (rs == 1)
            {
                result1.Visible = true;
                result1.Text = "Record Has Been Added Successfully !";
                Response.AddHeader("REFRESH", "5; URL = Schedule.aspx");

            }
            else
            {
                result1.Visible = true;
                result1.Text = "Please try again...";
            }

        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.ToString());
        }
Posted
Updated 3-May-19 3:09am
v4
Comments
Richard MacCutchan 3-May-19 9:21am    
You are trying to convert SelectedItem.Value, which most likely is not a string. Try the Text property instead.
Member 14075800 3-May-19 9:47am    
I tried. and same error occurred. Anyway, still thanks you much.
Richard MacCutchan 3-May-19 9:25am    
Sorry, my previous (deleted) answer was incorrect, the problem I suspect is as my comment above.
Member 14075800 3-May-19 9:40am    
Alright, it's okay. thanks again.
I feel really confuse, as I tried to use the exactly same code in a new web form, it can be inserted well without any conversion error. But back to the real web form, it comes out with the error.. I got really no idea for it, maybe I should check again.. hmm...
Richard MacCutchan 3-May-19 10:01am    
You need to stop guessing, and look at exactly what data is returned from the SelectedItem. Until you can see what you are trying to convert you will not solve the problem.

Start by using the debugger to look at exactly what you are passing to which field.
Identify which is the date / time value and look at the exact format you are passing it in - If it's a genuine date or time then you're fine.
Convert it to a DateTime value using TryParse (or TryParseExact) and pass that converted value to SQL instead of the "raw" value you are reading from your drop down.
Chances are that the values in your drop down are strings, and they don't have a format that is the same as dates are configured on your SQL Server machine, so it throws an exception because it can't convert it correctly. By passing DateTime values, you eliminate that problem.
 
Share this answer
 
Comments
Member 14075800 3-May-19 9:14am    
Thanks for the suggestion, I'm still finding way to solve it.
First convert the value in proper format

// Place a breakpoint here and see what dateFormat looks like

var classstartFormat = Convert.ToString(timedd.SelectedItem.Value);

// Using the format that you see, use DateTime.ParseExact() to properly read this value into a DateTime object
DateTime classstart= DateTime.ParseExact(classstartFormat,"yyyy-MM-dd", null);

// Set the parameter to the value
cmd.Parameters.AddWithValue("@classStart", classstart);
 
Share this answer
 
v3
Comments
Member 14075800 3-May-19 9:15am    
Thanks, I had just tried, but it tells that "String was not recognized as a valid DateTime" ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900