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

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

Showing database rows in a grid

The shortest path from a database to a screen is a query, a data table and a grid. This lesson walks that path once.

The three steps

  1. Open a connection using a connection string.
  2. Run a command and fill a data table with the rows.
  3. Bind the table to a grid so the rows appear.
C#
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand("SELECT Id, Name FROM Product", conn))
{
    var table = new DataTable();
    conn.Open();
    new SqlDataAdapter(cmd).Fill(table);
    productsGrid.DataSource = table;
    productsGrid.DataBind();
}

Why bind rather than loop

A grid turns rows into markup for you. Binding once is clearer and less error prone than building a table by hand.

Never build a query from typed text. Joining user input into a query string invites trouble. The next lesson, reading rows with a parameterised query, shows the safe way.

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.