Navigate a many-to-many relationship. : DataRelation « ADO.Net « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » ADO.Net » DataRelation 
32.38.1.Navigate a many-to-many relationship.
using System;
using System.Data;
using System.Data.SqlClient;

public class AddCustomer
{
  public static void Main() 
  {
    string connectionString = "Data Source=localhost;Initial Catalog=pubs;Integrated Security=SSPI";
    string SQL = "SELECT au_lname, au_fname, au_id FROM Authors";

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(SQL, con);
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();

    con.Open();
    adapter.Fill(ds, "Authors");

    cmd.CommandText = "SELECT au_id, title_id FROM TitleAuthor";
    adapter.Fill(ds, "TitleAuthor");

    cmd.CommandText = "SELECT title_id, title FROM Titles";
    adapter.Fill(ds, "Titles");
    con.Close();

    DataRelation titles_titleAuthor = new DataRelation("", ds.Tables["Titles"].Columns["title_id"], ds.Tables["TitleAuthor"].Columns["title_id"]);

    DataRelation authors_titleAuthor = new DataRelation("", ds.Tables["Authors"].Columns["au_id"], ds.Tables["TitleAuthor"].Columns["au_id"]);

    ds.Relations.Add(titles_titleAuthor);
    ds.Relations.Add(authors_titleAuthor);

    foreach (DataRow rowAuthor in ds.Tables["Authors"].Rows)
    {
        Console.WriteLine(rowAuthor["au_fname"]);
        Console.WriteLine(rowAuthor["au_lname"]);
        foreach (DataRow rowTitleAuthor in rowAuthor.GetChildRows(authors_titleAuthor))
        {
            foreach (DataRow rowTitle in rowTitleAuthor.GetParentRows(titles_titleAuthor))
            {
                Console.WriteLine(rowTitle["title"]);
            }
        }
    }
  }
}
32.38.DataRelation
32.38.1.Navigate a many-to-many relationship.
32.38.2.Define DataRelation
32.38.3.DataRelation Example
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.