Getting Started with ADO.NET
Enough theory! Let’s write some code and see how this works. Working with ADO.NET can be complex, but for many queries, the model is surprisingly simple.
In this example, create a simple Windows Form, with a single list box
in it called lbCustomers
. Populate this list box
with bits of information from the Customers table in the Northwind
database.
Begin by creating a DataAdapter
object:
SqlDataAdapter DataAdapter = new SqlDataAdapter( commandString, connectionString);
The two parameters are
commandString
and
connectionString
. The
commandString
is the SQL statement that will
generate the data you want in your DataSet
:
string commandString = "Select CompanyName, ContactName from Customers";
The connectionString
is whatever string is needed
to connect to the database. In my case, I’m running
SQL Server on my development machine where I have left the system
administrator (sa
) password blank (I know, I
know, not a good idea. I’ll fix it by the time this
book is released. Honest.):
string connectionString = "server=localhost; uid=sa; pwd=; database=northwind";
If you do not have SQL Server installed, select Samples and Quickstart Tutorials from the Microsoft .NET Framework SDK program group. A web page appears, giving you the option to install the .NET Framework Samples Database, which includes an installation of SQL Server. After you install the samples database, set up the QuickStarts (this will create the northwind sample database). To use this database, ...
Get Programming C#, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.