Reputation: 1794
I have the following html in an aspx so it is already in a form:-
<asp:TextBox ID="Name" runat="server" MaxLength="50" Width="175px"></asp:TextBox>
I have a button:-
<asp:Button ID="updateDetails" Text="Update Details" runat="server" OnClick="updateDetails_Click" />
In the code behind I have the updateDetails_Click
proc:-
protected void updateDetails_Click(object sender, EventArgs e)
{
utils utils = new utils();
string connectionString = ConfigurationManager.ConnectionStrings[utils.liveTest() + "arenadestinationsConnectionString"].ToString();
string SQL = "UPDATE Users SET "
+ "Name = @Name, "
+ "WHERE IdUser = @iDUser";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(SQL, connection);
command.Parameters.AddWithValue("@Name", Name.Text);
command.Parameters.AddWithValue("@iDUser", Session["loggedIn"].ToString());
try
{
connection.Open();
command.ExecuteReader();
}
catch
{
}
finally
{
connection.Close();
}
}
}
If I type new text into the Name textbox, when I click on the Update Details button, the Name.Text always shows the original text, never the modified text.
What am I doing wrong? I'm converting myself from VB to C# so I will no doubt have a few tricks to learn.
Upvotes: 0
Views: 420
Reputation: 63956
You can't update any records calling ExecuteReader
as this is for SELECT statements (reading data). If you want to update the data in the DB, you must call ExecuteNonQuery
So change your code to:
command.ExecuteNonQuery();
Upvotes: 4
Reputation: 25337
Change:
command.ExecuteReader();
to
command.ExecuteNonQuery(); // This is for insert, update, delete
and you can leave out the @
in:
command.Parameters.AddWithValue("Name", Name.Text);
command.Parameters.AddWithValue("iDUser", Session["loggedIn"].ToString());
Upvotes: 3