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...
protected void Page_Load(object sender, EventArgs e)
{
DateTime StartTime = DateTime.MinValue.AddHours(8);
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());
}