using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Data;
using HieararchySelectionChanged.NORTHWNDDataSetTableAdapters;

namespace HieararchySelectionChanged
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.InitializeHierarchy();
        }

        private void InitializeHierarchy()
        {
            NORTHWNDDataSet dataSet = new NORTHWNDDataSet();

            Order_DetailsTableAdapter detailTableAdapter = new Order_DetailsTableAdapter();
            detailTableAdapter.Fill(dataSet.Order_Details);

            OrdersTableAdapter tableAdapter = new OrdersTableAdapter();
            tableAdapter.Fill(dataSet.Orders);

            radGridView1.AutoGenerateHierarchyFromDataSet = false;

            this.radGridView1.ItemsSource = dataSet.Tables["Orders"];
            this.radGridView1.DataMember = dataSet.Tables["Orders"].TableName;

            GridViewTableDefinition definition = new GridViewTableDefinition();
            definition.AutoGenerateFieldDescriptors = false;
            definition.DataSource = dataSet.Tables["Order Details"];

            GridViewDataColumn order = new GridViewDataColumn();
            order.UniqueName = "OrderID";
            order.HeaderText = "OrderID";
            order.DataType = typeof(int);

            GridViewDataColumn product = new GridViewDataColumn();
            product.UniqueName = "ProductID";
            product.HeaderText = "ProductID";
            product.DataType = typeof(int);

            TableRelation relation = new TableRelation();
            relation.FieldNames.Add(new FieldDescriptorNamePair("OrderID", "OrderID"));
            definition.Relation = relation;

            definition.FieldDescriptors.Add(order);
            definition.FieldDescriptors.Add(product);

            this.radGridView1.TableDefinition.ChildTableDefinitions.Add(definition);
        }

        private void radGridView1_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            GridViewDataControl dataControl = (GridViewDataControl) e.DataControl;
            GridViewExpandableRow parentRow = (dataControl.ParentRow as GridViewExpandableRow);

            if (parentRow != null)
                MessageBox.Show("This is the child grid!");
        }
    }
}
