0

When I try to save the details I get an error message saying the following.

enter image description here

How do I convert this to string value? Thanks in advance! Here is my C# code and the error message.

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\GCSCFC.mdf;Integrated Security=True;Connect Timeout=30");

    try
    {
        string sql = "INSERT INTO Leave (Employee_ID, Leave_Type,Leave_Date,Leave_Time_From, Leave_Time_To) values('" + txtEmpID.Text + "','" + cmbLeaveType.Text + "','" + PickerLeaveDate.Text + "','" + txtTimeFrom.Text + "','" + txtTimeTo.Text + "')";

        SqlCommand exesql = new SqlCommand(sql, cn);
        cn.Open();

        exesql.ExecuteNonQuery();

        MessageBox.Show("New Employee Added Successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        cn.Close();
    }
}
6
  • 4
    Possible SQL Injection Use parameter binding and your code will work instead of manually adding '. Commented Dec 25, 2015 at 19:20
  • What are your input values? Commented Dec 25, 2015 at 19:29
  • My input values would be like, Employee_ID=0001, Leave_Type=Casual, Leave_Date=26/12/2015, Leave_Time_From= 12 am, Leave_Time_To=7 pm @Sybren Commented Dec 25, 2015 at 19:34
  • 2
    The error messge is pretty clear. You are trying to store a string inside a field that expects a datetime value. Putting your values between single quote means the everything is a string not a datetime. You really need to start using parameterized queries where you could prepare parameters of the correct type expected by the database table Commented Dec 25, 2015 at 19:39
  • 1
    Right, but you are the mercy of whatever the database programmer has thought a string representing a date should be. No, there is only a correct way to do this. Parameters. Commented Dec 25, 2015 at 20:05

1 Answer 1

1

Use parameters when database column is a DataTime like code below

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\GCSCFC.mdf;Integrated Security=True;Connect Timeout=30");
            try
            {
                string sql = "INSERT INTO Leave (Employee_ID, Leave_Type,Leave_Date,Leave_Time_From, Leave_Time_To) values('" + @txtEmpID + "','" + @cmbLeaveType + "','" + @PickerLeaveDate + "','" + @txtTimeFrom + "','" + @txtTimeTo + "')";
                SqlCommand exesql = new SqlCommand(sql, cn);
                exesql.Parameters.Add("@txtEmpID", SqlDbType.VarChar);
                exesql.Parameters.Add("@cmbLeaveType", SqlDbType.VarChar);
                exesql.Parameters.Add("@PickerLeaveDate", SqlDbType.DateTime);
                exesql.Parameters.Add("@txtTimeFrom", SqlDbType.VarChar);
                exesql.Parameters.Add("@txtTimeTo", SqlDbType.VarChar);

                exesql.Parameters["@txtEmpID"].Value = txtEmpID.Text;
                exesql.Parameters["@cmbLeaveType"].Value = cmbLeaveType.Text;
                exesql.Parameters["@PickerLeaveDate"].Value = PickerLeaveDate.Value;
                exesql.Parameters["@txtTimeFrom"].Value = txtTimeFrom;
                exesql.Parameters["@txtTimeTo"].Value = txtTimeTo.Text;

                cn.Open();
                exesql.ExecuteNonQuery();
                MessageBox.Show("New Employee Added Successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cn.Close();
            }
        }
​
Sign up to request clarification or add additional context in comments.

2 Comments

And even better: use your SqlConnection and SqlCommand inside a using(.....) { ...... } construct which frees you from having to use a finally block and ensures proper and immediate disposal of those objects when no longer needed!
The code is in a function so the variables are local on the stack and will be automatically dispose when the function terminates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.