I have a button within my web page to inserts a few values into sql server columns. One of these values happens to be of data type Date. The following is my code for my asp.net page:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values ('TextBox2.Text', 'TextBox1.Text', 'FA0005')",con);
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
//Label5.Text = dl.Tables[0].Rows[1][9].ToString();
}
I want to be able to have the user enter the date in the format (yyyy-MM-dd), which is the date format for my sql server. “TextBox2” is the textbox that holds the date input. Whenever I simply hard code the date as for ex. ‘2010-01-01′, ’50’, ‘FA0005’, it works well and inserts the record. However, when I code is as ‘TextBox2.Text’, ‘TextBox1’,etc. It gives me an error saying “Conversion failed when converting date and/or time from character string”. Can someone help me with this? Its confusing me because having the date in ‘yyyy-mm-dd’ format works well, which is same as the textbox.
Now, let’s break down the
string.Formatfunction. It says that if I have a string to format like this"Hello {0}!", anything I pass in at the zero index of the function will replace every occurrance of{0}. So, let’s say I have this string"Hello {0}, and I say again hello {0}!"and I used it like thisstring.Format("Hello {0}, and I say again hello {0}!", "world"), I would get a string like this"Hello **world**, and I say again hello **world**!".Note
However, the above solution leaves you open to SQL Injection, so if you want to protect against that then let’s go this route.
Now let’s break this down. The statement sent to the SQL server is just what you see, with the
@paramnamein the string. But, it will send it as aprepareand prepare that statement with the values you provided in theAddParameterWithValuemethod. Note that here, as long as the value in theTextBox2.Textis a date you don’t have to concern yourself with the format because SQL server will take care of that. Bear in mind that SQL server stores it in one format and you’ll display it in another but it can convert from a myriad of formats as long as they are valid.Now, as stated by @Willem, it would behoove you to ensure that the value in
TextBox2.Textis in fact a date, so let’s do that, add this snippet at the top of the function …… and then modify the line with the
AddParameterWithValuelike this …