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

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

Adding a new row

An insert adds a row. The database usually assigns the identifier, and you often need it straight away.

The insert

C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(
    "INSERT INTO Product (Name, Price) " +
    "VALUES (@name, @price); SELECT SCOPE_IDENTITY();", conn))
{
    cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
    cmd.Parameters.AddWithValue("@price", decimal.Parse(txtPrice.Text));
    conn.Open();
    object newId = cmd.ExecuteScalar();
    statusLabel.Text = "Created record " + newId;
}

What to notice

  • The command both inserts and returns the new identifier in one trip.
  • ExecuteScalar is used because a single value comes back.
  • The value from a text box is converted before it is used.
Check your input first. If the price box holds a word rather than a number, the conversion fails. Guard it with validation, as shown in checking that a number falls in range.

Removing a row is the last of the four operations, in removing a 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.