Microsoft KB Archive/314145

= How To Populate a DataSet Object from a Database by Using Visual C# .NET =

Article ID: 314145

Article Last Modified on 3/29/2007

-

APPLIES TO


 * Microsoft ADO.NET 1.0
 * Microsoft ADO.NET 1.1
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# .NET 2003 Standard Edition

-



This article was previously published under Q314145



For a Microsoft Visual Basic .NET version of this article, see 301216.

This article refers to the following Microsoft .NET Framework Class Library namespace:
 * System.Data.SqlClient

IN THIS TASK
SUMMARY
 * Requirements
 * Filling a DataSet
 * Complete Code Listing

REFERENCES



SUMMARY
DataSet objects, a key part of data access in the Microsoft .NET Framework, are in-memory objects that can hold tables, views, and relationships. This article demonstrates how to fill a DataSet object with the results of one or more database queries and how to access that data after it is loaded into the DataSet object.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
 * Microsoft SQL Server 7.0, Microsoft SQL Server 2000, or Microsoft Data Engine with the Pubs sample database installed
 * Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:
 * Database terminology
 * Structured Query Language (SQL)

back to the top

Filling a DataSet
Using a variety of objects from within the System.Data namespace, you can connect to a database server, run a query, and have the results placed into a DataSet object. The DataSet is a disconnected object. Therefore, after the data is loaded, the connection to the database is no longer used until you want to load more data or update the server with the changes you have made to your in-memory copy of the information.

To load data from a database into a DataSet, follow these steps:  Start Visual Studio .NET. Create a new Console Application project in Visual C# .NET. Visual Studio .NET creates a Static Class for you, along with an empty Main procedure. Make sure that the project references the System and System.Data namespaces.  Use the using statement on the System, System.Data, and System.Data.SqlClient namespaces so that you are not required to qualify declarations from these namespaces later in your code. You must use these statements before any other declarations. using System; using System.Data; using System.Data.SqlClient;   The first step to get data from the database to the DataSet is to establish a database connection, which requires a System.Data.SqlClient.SqlCommand object and a connection string. The connection string in the code to follow connects a SQL Server server that is located on the local computer (the computer where the code is running). You must modify this connection string as appropriate for your environment. After the SqlConnection object is created, call the Open method of that object to establish the actual database link. string sConnectionString; sConnectionString = &quot;Password=myPassword;User ID=myUserID;&quot; + &quot;Initial Catalog=pubs;&quot; + &quot;Data Source=(local)&quot;; SqlConnection objConn = new SqlConnection(sConnectionString); objConn.Open;   Create a DataAdapter object, which represents the link between the database and your DataSet object. You can specify SQL or another type of command that is used to retrieve data as part of the constructor object of the DataAdapter. This sample uses a SQL statement that retrieves records from the Authors table in the Pubs database. SqlDataAdapter daAuthors = new SqlDataAdapter(&quot;Select * From Authors&quot;, objConn);   You must declare and create an instance of a DataSet object, at which time you can supply a name for the entire DataSet before you can start to load any data. The name may contain several distinct tables. DataSet dsPubs = new DataSet(&quot;Pubs&quot;); </li>  The SqlDataAdapter class provides two methods, Fill and FillSchema, that are crucial to loading this data. Both of these methods load information into a DataSet. Fill loads the data itself, and FillSchema loads all of the available metadata about a particular table (such as column names, primary keys, and constraints). A good way to handle the data loading is to run FillSchema followed by Fill. For example: daAuthors.FillSchema(dsPubs,SchemaType.Source, &quot;Authors&quot;); daAuthors.Fill(dsPubs,&quot;Authors&quot;); If you only use Fill, you can only load the basic metadata that is required to describe the column names and data types. The Fill method does not load primary key information. To change this default behavior, you can set the MissingSchemaAction property of the DataAdapter object to MissingSchemaAction.AddWithKey, which loads the primary key metadata along with the default information. For example: daAuthors.MissingSchemaAction = MissingSchemaAction.AddWithKey; daAuthors.Fill(dsPubs,&quot;Authors&quot;); </li>  The data is now available as an individual DataTable object within the Tables collection of the DataSet. If you specified a table name in the calls to FillSchema and Fill, you can use that name to access the specific table that you want. DataTable tblAuthors; tblAuthors = dsPubs.Tables[&quot;Authors&quot;]; </li>  You can use a For Each loop to loop through all of the DataRow objects within the Rows collection of a DataTable. This gives you access to each row of the table. You can access columns by name or by positional index (with '0' being the first column position). For example: foreach (DataRow drCurrent in tblAuthors.Rows) {   Console.WriteLine(&quot;{0} {1}&quot;,        drCurrent[&quot;au_fname&quot;].ToString,        drCurrent[&quot;au_lname&quot;].ToString); } Console.ReadLine; </li> Save your project. On the Debug menu, click Start to run your project and make sure that it works.</li></ol>

back to the top

Complete Code Listing
using System; using System.Data; using System.Data.SqlClient;

namespace PopulateDataSet {   ///     /// Summary description for Class1. ///    class Class1 {       static void Main(string[] args) {           string sConnectionString; sConnectionString = &quot;Password=myPassword;User ID=myUserID;&quot; + &quot;Initial Catalog=pubs;&quot; + &quot;Data Source=(local)&quot;; SqlConnection objConn = new SqlConnection(sConnectionString); objConn.Open;

SqlDataAdapter daAuthors = new SqlDataAdapter(&quot;Select * From Authors&quot;, objConn); DataSet dsPubs = new DataSet(&quot;Pubs&quot;); daAuthors.FillSchema(dsPubs,SchemaType.Source, &quot;Authors&quot;); daAuthors.Fill(dsPubs,&quot;Authors&quot;);

DataTable tblAuthors; tblAuthors = dsPubs.Tables[&quot;Authors&quot;];

foreach (DataRow drCurrent in tblAuthors.Rows) {               Console.WriteLine(&quot;{0} {1}&quot;,                    drCurrent[&quot;au_fname&quot;].ToString,                    drCurrent[&quot;au_lname&quot;].ToString); }           Console.ReadLine; }   } } back to the top

<div class="references_section">