protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand(string.Format("insert into dbo.FillTable values ('{0}', '{1}', 'FA0005')", TextBox2.Text, TextBox1.Text), con);
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
}
Now, let's break down the string.Format
function. 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 this string.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.
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values (@TextBox2Val, @TextBox1Val, 'FA0005')", con);
cmd1.AddParameterWithValue( "TextBox1Val", TextBox1.Text );
cmd1.AddParameterWithValue( "TextBox2Val", TextBox2.Text );
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
}
Now let's break this down. The statement sent to the SQL server is just what you see, with the @paramname
in the string. But, it will send it as a prepare
and prepare that statement with the values you provided in the AddParameterWithValue
method. Note that here, as long as the value in the TextBox2.Text
is 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.Text
is in fact a date, so let's do that, add this snippet at the top of the function ...
DateTime theDate;
if (!DateTime.TryParse(TextBox2.Text, out theDate))
{
// throw some kind of error here or handle it with a default value
...
}
... and then modify the line with the AddParameterWithValue
like this ...
cmd1.AddParameterWithValue( "TextBox2Val", theDate );