Creating a Data Set From Scratch in C#

In a previous post, I outlined the process of creating a DataSet graphically using the Visual Studio Data Set Designer. In this post, however, I am going to go through how to create a Date Set from scratch in code. Sometimes it takes doing something from scratch to learn more about the namespaces and classes.

The System.Data namespace provides access to the ADO.NET architecture. It contains several classes that are used to build and interact with data sets.

DataSet
DataTable
DataRow
DataColumn

The below example is simple, but it shows the classes in action.

C# Program Listing

using System;
using System.Data;

namespace CrtDataSet
{
    class Program
    {
        static void Main(string[] args)
        {
            //-- Instantiate the data set and table
            DataSet SongDS = new DataSet();
            DataTable songTable = SongDS.Tables.Add();

            //-- Add columns to the data table
            songTable.Columns.Add("ID", typeof(int));
            songTable.Columns.Add("Band", typeof(string));
            songTable.Columns.Add("Song", typeof(string));

            //-- Add rows to the data table
            songTable.Rows.Add(1, "Breaking Benjamin", "Diary of Jane");
            songTable.Rows.Add(2, "Three Days Grace", "Pain");
            songTable.Rows.Add(3, "Seether", "Fake It");
            songTable.Rows.Add(4, "Finger Eleven", "Paralyzer");
            songTable.Rows.Add(5, "Three Doors Down", "Citizen Soldier");

            //-- Cycle thru the data table printing the values to the screen
            foreach (DataTable table in SongDS.Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    Console.WriteLine(row["Band"] + " ~ " + row["Song"]);
                }
            }
        }
    }
}

C# Listing on GitHub

DataSet/DataTable in Debug Mode

datasetvisualizer.gif

Result to Console

result1.gif

In a future post, I will be exploring other classes of the System.Data namespace.

kick it on DotNetKicks.com

Posted on January 12, 2008, in C#. Bookmark the permalink. 3 Comments.

  1. hi , how do i setup a new project to begin with, i dont think im picking the right settings :/

  2. Thanks… simple and to the point :)

  1. Pingback: Why Code when you can Steal « Analyze the Data not the Drivel.

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.