using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using System.Collections;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{


  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
  {
    //save the expanded/selected state in the session
    if (e.CommandName == RadGrid.ExpandCollapseCommandName)
     {
      //Is the item about to be expanded or collapsed
      if (!e.Item.Expanded)
      {
        //Save its unique index among all the items in the hierarchy
        HttpCookie c = new HttpCookie(ConstructHashKey((GridDataItem)e.Item));
        c.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(c);
      }
      else //collapsed
      {
        HttpCookie cookie = Request.Cookies[ConstructHashKey((GridDataItem)e.Item)];
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie);

      }
    }
    else if (e.CommandName == RadGrid.DeleteCommandName)
    {
      HttpCookie cookie = Request.Cookies[ConstructHashKey((GridDataItem)e.Item)];
      if (cookie != null)
      {
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie);
      }
    }
  }

  protected void RadGrid1_DataBound(object sender, EventArgs e)
  {
    object[] cookies = new object[Request.Cookies.Count];

    if (Request.Cookies.Count > 0)
    {
      Request.Cookies.CopyTo(cookies, 0);

      foreach (HttpCookie cookie in cookies)
      {
        GridDataItem item = GetItemByDataKey(cookie.Name);

        if (item != null)
          item.Expanded = true;
      }
    }

  }

  protected GridDataItem GetItemByDataKey(string dataKey)
  {
 
    foreach (GridDataItem item in RadGrid1.Items)
    {
       if (ConstructHashKey(item) == dataKey)
       {
         return item;
       }
    }   

    return null;
  }

  protected string ConstructHashKey(GridDataItem item)
  {
    string hashKey = "";
    int i = 0;

    hashKey = item.OwnerTableView.HierarchyIndex + "_";

    foreach (string dataKeyName in item.OwnerTableView.DataKeyNames)
    {
      if (i != 0)
        hashKey += "_";

      hashKey += item.GetDataKeyValue(dataKeyName);
    }

    return hashKey;
  }

  protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e)
  {
    RadGrid1.Rebind();
  }
}