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.