Reputation: 2305
I have some textboxes that are populated with customer info from a database (name, address) on page load. I want users to be able to simply change this and click a button to update their personal information.
I have the following code that runs on button click:
con.Open();
string query = "UPDATE CustomerInfo SET FirstName=@FirstName, LastName=@LastName, Address=@Address, PostalCode=@PostalCode, PostalName=@PostalName WHERE UserName=@UserName";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
cmd.Parameters.AddWithValue("@Address", SqlDbType.VarChar).Value = txtAddress.Text;
cmd.Parameters.AddWithValue("@PostalCode", SqlDbType.Int).Value = txtPostalCode.Text;
cmd.Parameters.AddWithValue("@PostalName", SqlDbType.VarChar).Value = txtPostalName.Text;
cmd.Parameters.AddWithValue("@UserName", SqlDbType.VarChar).Value = UserName;
cmd.ExecuteNonQuery();
con.Close();
This does not work. If I change the textbox to something different and click the button, nothing happens. The table is not updated with the new values, and I get no error messages. However, if I change the Parameter values from for example txtFirstName.Text
to "Bob"
, it successfully updates the FirstName column in my table to Bob.
Not sure what I'm missing, but for some reason using textbox.Text as value doesn't work.
Upvotes: 1
Views: 4335
Reputation: 98868
AddWithValue
takes parameter value as a second parameter, not SqlDbType
.
You are mixing it with Add
method.
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
Also use using
statement to dispose your SqlConnection
and SqlCommand
.
EDIT: Ok, that's not the point as you said (And I can't delete my answer because of 5 answer delete limit). I really doubt that your textbox values change in your page life-cycle. By the way, where did you defined these code? Be sure that your textbox values keep their values since these codes were execute.
Upvotes: 2