Reputation: 839
I need to store the date fetch from the ASP.Net text box into a SQL Server 2008 date
column.
I am getting the following exception message.
Conversion failed when converting date and/or time from character string.
My code is:
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
int n=4;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(<Connection String>);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values('" + TextBox1.Text + "')";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Please help ..
Thanks in advance
Upvotes: 1
Views: 1399
Reputation: 2938
you have to do multiple changes
Your code would be like that
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
int n=4;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(<Connection String>);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values(@date))";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@date",Convert.DateTime(TextBox1.Text));
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Upvotes: 0
Reputation: 744
Upvotes: 0
Reputation: 7747
Change your code to the following (assuming the column in temp
is actually a DateTime
):
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values(@Value)";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@Value", DateTime.Parse(TextBox1.Text));
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
You should also change your logic to validate that TextBox1.Text
is actually a valid date.
Upvotes: 4