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

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

Reading rows with a parameterised query

When a query depends on a value the visitor supplied, that value must travel as a parameter, never as part of the query text.

The parameter pattern

C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(
    "SELECT Id, Name FROM Product WHERE Category = @cat", conn))
{
    cmd.Parameters.AddWithValue("@cat", ddlCategory.SelectedValue);
    var table = new DataTable();
    conn.Open();
    new SqlDataAdapter(cmd).Fill(table);
    resultsGrid.DataSource = table;
    resultsGrid.DataBind();
}

Why this matters

  • The value is treated as data, not as part of the command, which closes the door on injection.
  • The type is handled for you, so a date or a number arrives intact.
  • The same command can run many times with different values.
One habit worth keeping for life. If you ever find yourself gluing text into a query, stop and use a parameter instead. It is almost always less code anyway.

The same pattern writes data, beginning with 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.