DataRelation Example : DataRelation « ADO.Net « C# / CSharp Tutorial






using System;
using System.Data;            
using System.Data.SqlClient;  
using System.Collections.Generic;
using System.Text;

  class Program
  {
    static void Main(string[] args)
    {
      SqlConnection thisConnection = new SqlConnection(
                @"Data Source=.\SQLEXPRESS;" +
                @"AttachDbFilename='NORTHWND.MDF';" +
                @"Integrated Security=True;Connect Timeout=30;User Instance=true");
      SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers", thisConnection);

      SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

      DataSet thisDataSet = new DataSet();

      SqlDataAdapter custAdapter = new SqlDataAdapter("SELECT * FROM Customers", thisConnection);
      SqlDataAdapter orderAdapter = new SqlDataAdapter("SELECT * FROM Orders", thisConnection);
      custAdapter.Fill(thisDataSet, "Customers");
      orderAdapter.Fill(thisDataSet, "Orders");

      DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrders",
         thisDataSet.Tables["Customers"].Columns["CustomerID"],
         thisDataSet.Tables["Orders"].Columns["CustomerID"]);

      foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
      {
        Console.WriteLine("Customer ID: " + custRow["CustomerID"] +
                  " Name: " + custRow["CompanyName"]);
        foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
        {
          Console.WriteLine("  Order ID: " + orderRow["OrderID"]);
        }
      }
            custOrderRel.Nested = true;
            thisDataSet.WriteXml("nwinddata.xml");
            thisConnection.Close();
    }
  }








32.38.DataRelation
32.38.1.Navigate a many-to-many relationship.
32.38.2.Define DataRelation
32.38.3.DataRelation Example