// Arquivo de exemplo: DataRelation.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;

public partial class DataRelation1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ConnectionStringSettings getString = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings;
            if (getString != null)
            {
                string sSql = "Select CategoryID, CategoryName From Categories";
                string sSql1 = "Select CategoryID, ProductName From Products";
                using (SqlConnection conn = new SqlConnection(getString.ConnectionString))
                {
                    try
                    {
                        DataSet ds = new DataSet();
                        SqlDataAdapter adapter = new SqlDataAdapter(sSql, conn);
                        SqlDataAdapter adapter1 = new SqlDataAdapter(sSql1, conn);

                        adapter.Fill(ds, "Categorias");
                        adapter1.Fill(ds, "Produtos");

                        ds.Relations.Add("CategoriasProdutos",
                        ds.Tables["Categorias"].Columns["CategoryID"],
                        ds.Tables["Produtos"].Columns["CategoryID"]);

                        foreach (DataRow linhas in ds.Tables["Categorias"].Rows)
                        {
                            Response.Write("<p><b>Categoria:</b> " + linhas["CategoryName"] + "<br/>");
                            foreach (DataRow dr in linhas.GetChildRows("CategoriasProdutos"))
                            {
                                Response.Write("* " + dr["ProductName"] + "<br/>");
                            }
                        }
                    }
                    catch (SqlException)
                    {
                        Response.Write("Erro SQL.");
                    }
                    catch (InvalidOperationException)
                    {
                        Response.Write("Operação inválida.");
                    }
                    catch (Exception ex)
                    {
                        Response.Write("Erro ao executar código.");
                    }
                }
            }
        }
    }
}

