0

Hi guys i came stuck again. I am wanting to edit a selected row from my datagridview and replace the data from dgv with the new information in the text fields. I have managed to get it to change all the data in the dataset. So what i am asking is for guidance on how to code it so it only edits the selected row.

private void btnEdit_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(constring);
    SqlDataAdapter da = new SqlDataAdapter();
    da.UpdateCommand = new SqlCommand(String cmdUpdate = @"update Customer set firstName = @firstName, surname = @surname, email = @email, phonenumber = @phone, mobileNumber = @mobile";
    , con);
    da.UpdateCommand.Parameters.Add("@firstName", SqlDbType.VarChar).Value = textFirstName.Text;
    da.UpdateCommand.Parameters.Add("@surname", SqlDbType.VarChar).Value = textSurname.Text;
    da.UpdateCommand.Parameters.Add("@email", SqlDbType.VarChar).Value = textEmail.Text;
    da.UpdateCommand.Parameters.Add("@phone", SqlDbType.VarChar).Value = textPhone.Text;
    da.UpdateCommand.Parameters.Add("@mobile", SqlDbType.VarChar).Value = textMobile.Text;
    da.UpdateCommand.Parameters.Add("@ID", SqlDbType.Int).Value = customerDataSet.Customer[0].ID;

    con.Open();
    da.UpdateCommand.ExecuteNonQuery();
    MessageBox.Show("Customer Edited");
    con.Close(); 
}
3
  • What is your cmdUpdate looks like? Commented Oct 21, 2013 at 10:42
  • Why do you not simply change the datarow in the Dataset and throw that into the Update method of the DataAdapter? Commented Oct 21, 2013 at 10:49
  • Ralf i am completely new to this so not sure how to do that. I have been following some online tutorials and learning as i go. Sorry Commented Oct 21, 2013 at 11:01

1 Answer 1

1

You UPDATE query updates whole table you should use WHERE statement in this query to update the row with current ID

update Customer 
set firstName = @firstName, 
    surname = @surname, 
    email = @email, 
    phonenumber = @phone, 
    mobileNumber = @mobile
WHERE ID=@ID
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that its now updating row [0] but i can have a play about and see if i can get it working. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.