Every once in a while we receive support about how to create hierarchical grid directly from objects hierarchy and I decided to post small example how to achieve this easily:

  protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
  {
    RadGrid1.DataSource = MyList;
  }

  protected void RadGrid1_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
  {
    e.DetailTableView.DataSource = MyList.Find(
         delegate(Master master)
         {
           return master.ID == Convert.ToInt32(e.DetailTableView.ParentItem.GetDataKeyValue("ID"));
         }
       ).Details;
  }

  public List<Master> MyList
  {
    get
    {
        List<Master> items = new List<Master>();
        for (int i = 0; i < 5; i++)
       {
           Master item = new Master();
           item.ID = i;
           item.Name = String.Format("Item{0}", i);

           List<Detail> detailList = new List<Detail>();
           for (int j = 0; j < 5; j++)
           {
             Detail detailItem = new Detail();
            detailItem.ID = j;
             detailItem.Name = String.Format("Item{0}", j);
             detailItem.MasterID = i;
             detailList.Add(detailItem);
           }
 
           item.Details = detailList;
           items.Add(item);
        }
 
        return items;
      }
  }

  public class Master
  {
   public int ID { get; set; }
   public string Name { get; set; }
   public List<Detail> Details { get; set; }
  }

  public class Detail : Master
  {
     public int MasterID { get; set; }
  }

...
        <telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource"
           OnDetailTableDataBind="RadGrid1_DetailTableDataBind">
             <MasterTableView DataKeyNames="ID">
                 <DetailTables>
                    <telerik:GridTableView Width="100%" runat="server" />
                 </DetailTables>
             </MasterTableView>
        </telerik:RadGrid>
...

The key here is to handle DetailTableDataBind event where you can find easily desired item in your collection a get item details.

Enjoy!


About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks

Comments

Comments are disabled in preview mode.