using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class RadGridMasterDetailProgrammaticBind : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (RadGrid1.SelectedIndexes.Count == 0)
            RadGrid1.SelectedIndexes.Add(0);
        if (RadGrid2.SelectedIndexes.Count == 0)
        {
            RadGrid2.Rebind();
            RadGrid2.SelectedIndexes.Add(0);
        }
    }
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == "RowClick")
        {
            RadGrid2.Rebind();
        }
        else
        {
            RadGrid2.SelectedIndexes.Clear();
        }
    }
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = SqlDataSource1;
    }
    protected void RadGrid2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        if (RadGrid1.SelectedItems.Count > 0)
        {
            GridDataItem masterItem = RadGrid1.SelectedItems[0] as GridDataItem;
            string masterDataKeyID = masterItem.GetDataKeyValue("CustomerID").ToString();
            SqlDataSource2.SelectCommand =
                String.Format("SELECT [OrderID], [OrderDate], [CustomerID], [ShipCountry] FROM [Orders] WHERE [CustomerID] = '{0}'",
                masterDataKeyID);
            RadGrid2.DataSource = SqlDataSource2;
        }
    }
}