c# getting crazy with a simple insert into....
Hi all :)
Here is my problem:
| |
myCommand =new SqlCommand("insert into myTable values("@field1")", myConnection); myParam =new SqlParameter(); myParam.ParameterName = "@field1"; myParam.Value = myTextBox1.Text; myCommand.ExecuteNonQuery();
|
Whatever i write in myTextBox1.Text, in database i obtain ever a "null".
If i modify my insert like:"insert into myTable values('" + myTextBox1.Text + "')";
it work...but we know that it isnt a safe way to solve proble, thinking at sql iniection for example... So...a gentleman that show me where i wrong?
Thx in advance.
Have you added myParam to myCommand? And I don't think you need " in insert.. I'm not sure, but you should be able to write it like:
"insert into myTable values(@field1)"
Konstantin Gonikman wrote: |
| Have you added myParam to myCommand? And I don't think you need " in insert.. I'm not sure, but you should be able to write it like: "insert into myTable values(@field1)" |
|
Yes, on the upper code i've only made a copy/paste error :)
myCommand.Parameter.Add(myParam);
But still have null value :(
Hmmm.... I just tried the same and it works...
try
{
SqlCommand cm = new SqlCommand("insert into Categories (CategoryName) values (@f)", sqlConnection1);
SqlParameter p = new SqlParameter("@f", SqlDbType.NVarChar);
p.Value = "my text";
cm.Parameters.Add(p);
sqlConnection1.Open();
cm.ExecuteNonQuery();
sqlConnection1.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
There is only one difference:
Your's param Value is a string.
My Param's Value will be a textBox.text.
If i try with a string, works for me too.
Thx a lot for support :)
Konstantin Gonikman wrote: |
| Yes, but textBox.Text is a string as well |
|
so...is really madness :(
if i try: p.Value = "abcdefghjhghj";
works!
if i try:
p.Value = myTextBox.Text;
doesnt works...
but....why?!?
Konstantin Gonikman wrote: |
That's really strange!  |
|
Bah...sincerely dunno whats'up..
I've close project, reopen, rebuild solution and has worked.
Anyway, really thx for yours help :)