Reputation: 27
When I run my program and try to update it, it updates all the columns to the new data in textboxes I don't know how to tell it to do it for the certain username which is in a textbox (txtUsernameUser.Text
) table name is UserData
primary key is Username
. I just want to say thanks in advance for your time
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Graded unit Dev\BlackMarch\BlackMarch\bin\Debug\DataBaseBM.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("UPDATE UserData SET Username = @Username, Password = @Password, FirstName = @Firstname, Surname = @Surname, Age = @Age, Gender = @Gender, Mobile = @Mobile, Email = @Email", con);
con.Open();
cmd.Parameters.AddWithValue("@Username", txtUsernameUser.Text);
cmd.Parameters.AddWithValue("@Password", txtboxPass.Text);
cmd.Parameters.AddWithValue("@FirstName", txtboxFN.Text);
cmd.Parameters.AddWithValue("@Surname", txtboxSurname.Text);
cmd.Parameters.AddWithValue("@Age", txtboxAge.Text);
cmd.Parameters.AddWithValue("@Gender", txtboxGender.Text);
cmd.Parameters.AddWithValue("@Mobile", txtboxMobile.Text);
cmd.Parameters.AddWithValue("@Email", txtboxEmail.Text);
cmd.ExecuteNonQuery();
con.Close();
Upvotes: 1
Views: 160
Reputation: 133360
Add a proper where condition eg: if you can select the row with a YourID use it
"UPDATE UserData SET Username = @Username,
Password = @Password,
FirstName = @Firstname,
Surname = @Surname,
Age = @Age,
Gender = @Gender,
Mobile = @Mobile,
Email = @Email
WHERE YourID = @YourId"
Upvotes: 1
Reputation: 218808
Add a WHERE
clause to the UPDATE
statement to identify the subset of records which are being identified. Additionally, you don't want to update the Primary Key (since it shouldn't change anyway). So you can use that parameter and just modify the query:
SqlCommand cmd = new SqlCommand("UPDATE UserData SET Password = @Password, FirstName = @Firstname, Surname = @Surname, Age = @Age, Gender = @Gender, Mobile = @Mobile, Email = @Email WHERE Username = @Username", con);
or, for readability in this post...
UPDATE
UserData
SET
Password = @Password,
FirstName = @Firstname,
Surname = @Surname,
Age = @Age,
Gender = @Gender,
Mobile = @Mobile,
Email = @Email
WHERE
Username = @Username
Upvotes: 1