.netCoders Contact Us
Search:

Creating and Manipulating DataSets

The DataSet can be likened to an in-memory database. It is designed to hold one or more tables of data, and the relationships between them. The DataSet is similiar to the disconnected recordset in classic ASP, because server-side cursors are not used to navigate and retrieve the data.

Manipulate DataSet Relationships

The DataSet has two primary collections: a collection of Tables, and a collection of Relations. Using the Relations collection, a foreign-key relationship can be established for the tables in memory. Master-detail views make use of this parent-child relationship frequently, and when DataSets are used for adding and updating data, these relationships can serve as constaints.

The following example shows two queries to the Northwind database that fill a DataSet with rows from the Customers and Orders table. A relationship is then formed between the CustomerID in the Customers table and the CustomerID in the Orders table.

using System;
using System.Data;
using System.Data.SqlClient;

namespace LearningDataSets
{
    class RelationsExample
    {
        static void Main(string[] args)
        {
            //Queries
            string sql1 = "select * from customers";
            string sql2 = "select * from orders";
            string connstring = "Server=localhost;Database=Northwind;UID=sa;Password=;";

            //Fill DataSet
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sql1, connstring);
            da.Fill(ds, "Customers");
            da.SelectCommand.CommandText = sql2;
            da.Fill(ds, "Orders");

            //Establish Relation
            ds.Relations.Add("CustomerOrderRelation",
                ds.Tables["Customers"].Columns["CustomerID"],
                ds.Tables["Orders"].Columns["CustomerID"]);
        }
    }
}