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
- Open a connection using a connection string.
- Run a command and fill a data table with the rows.
- 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.