Typed DataSets in C#

DataSets are an important aspect of .NET development. There are many ways to create and access them. In this entry, I will go through the process of creating a DataSet visually and then access that DataSet programatically.To add a DataSet Right-Click on the project and select > Add > New Item

20060703_pic1.jpg
—–

Once in the DataSet designer, go to the DataSet Toolbox and drag over TableAdapter and setup your connection – in this case I am using Pubs.

20060703_pic2.jpg
—–

Save the connection string to the application configuration file

20060703_pic3.jpg
—–

Select [Use SQL statements] as the Command type

20060703_pic4.jpg
—–

Enter the SQL statement to be used for this dataset. In this case I am extracting just authors from CA.

20060703_pic5.jpg
—–

Generate Methods to Fill and Get a DataTable

20060703_pic6.jpg
—–

After the DataSet is built, it should look like the below in the designer.

20060703_pic8.gif

—–

Once the dataset is created, it is accessible from the anywhere in the project. Below is how to interface with the dataset from a program.

First, a reference to the DataSet needs to be added to the Using section at the top. Intellisence should pick it up.

20060703_pic9.gif

—–

The code below is used to access the dataset:

// Access Table Adapter
authorsTableAdapter ta = new authorsTableAdapter();

// Access Dataset
dsPubsCA.authorsDataTable dt = ta.GetData();

—–

To keep this program simple, I am only going to access the DataSet and cycle thru it — printing data to the console.

C# Program Listing

Results:

20060703_pic10.gif

—–

As I said earlier, there are many ways t o create and access DataSets and this is just one of them. If you want code that is free of large SQL select commands, this is a way to cleanly access a Typed DataSet with just two lines of code.

Posted on July 3, 2006, in C#. Bookmark the permalink. 1 Comment.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.