Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Changing a row safely

An update changes an existing row. The pattern is the same as a parameterised read, with an important extra check.

The command

C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(
    "UPDATE Product SET Name = @name WHERE Id = @id", conn))
{
    cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
    cmd.Parameters.AddWithValue("@id", productId);
    conn.Open();
    int changed = cmd.ExecuteNonQuery();
    statusLabel.Text = changed + " row updated";
}

Why check the count

The execute method returns how many rows changed. If the answer is zero, the record was not found. If it is more than one, your condition matched too much. Either way, you want to know.

Always name the key. An update without a precise condition changes every row in the table. The identifier in the where clause is what keeps the change narrow.

Creating a row is the mirror of this, covered in adding a new row.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.