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
—–
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.
—–
Save the connection string to the application configuration file
—–
Select [Use SQL statements] as the Command type
—–
Enter the SQL statement to be used for this dataset. In this case I am extracting just authors from CA.
—–
Generate Methods to Fill and Get a DataTable
—–
After the DataSet is built, it should look like the below in the designer.

—–
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.

—–
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.
Results:

—–
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.







Pingback: Creating a Data Set From Scratch in C# « Rhonda Tipton’s WebLog