O'Reilly logo

ADO.NET in a Nutshell by Bill Hamilton, Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Performing a Query with a DataReader

To retrieve records with a Command and DataReader, you need to use the SELECT statement, which identifies the table and rows you want to retrieve, the filter and ordering clauses, and any table joins:

SELECT columns FROM tables WHERE search_condition

       ORDER BY order_expression ASC | DESC

When writing a SELECT statement with a large table, you may want to limit the number of returned results to prevent your application from slowing down dramatically as the database grows. Typically, you accomplish this by adding a WHERE clause that limits the results.

Example 5-1 shows a sample Windows application that fills a list box with the results of a query. The designer code is omitted.

Example 5-1. Using a fast-forward DataReader
// DataReaderFillForm.cs - Fills a ListBox using System; using System.Windows.Forms; using System.Data.SqlClient; public class DataReaderTest : Form { private ListBox lstNames; private string connectionString = "Data Source=localhost;" + "Initial Catalog=Northwind;Integrated Security=SSPI"; public DataReaderTest() { lstNames = new ListBox(); lstNames.Dock = DockStyle.Fill; Controls.Add(lstNames); Load += new EventHandler(DataReaderTest_Load); } public static void Main() { DataReaderTest t = new DataReaderTest(); Application.Run(t); } private void DataReaderTest_Load(object sender, System.EventArgs e) { string SQL = "SELECT ContactName FROM Customers"; // Create ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required