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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    Dictionary<string, bool> currentValues = new Dictionary<string, bool>();

    protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "UpdateAll")
        {
            foreach (GridEditableItem editedItem in RadGrid1.EditItems)
            {
                Hashtable newValues = new Hashtable();
                //The GridTableView will fill the values from all editable columns in the hash
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                SqlDataSource1.UpdateCommand = String.Format("Update Products SET Discontinued='{0}' WHERE ProductID='{1}'"
                    , newValues["Discontinued"], editedItem.GetDataKeyValue("ProductID").ToString());
                SqlDataSource1.Update();
                editedItem.Edit = false;
            }
            RadGrid1.Rebind();
        }

        if (e.CommandName == RadGrid.EditCommandName)
        {
            foreach (GridItem editedItem in RadGrid1.EditItems)
            {
                GridDataItem item = editedItem as GridDataItem;
                bool isChecked = (item["Discontinued"].Controls[0] as CheckBox).Checked;
                string key = item.GetDataKeyValue("ProductID").ToString();
                if (currentValues.ContainsKey(key))
                {
                    currentValues[key] = isChecked;
                }
                else
                {
                    currentValues.Add(key, isChecked);
                }
            }
        }
        
    }

    protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridDataItem && e.Item.IsInEditMode)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            //Hides the Update button for each edit form
            dataItem["EditCommandColumn"].Controls[0].Visible = false;
            string key = (dataItem.DataItem as DataRowView)["ProductID"].ToString();
            if (currentValues.ContainsKey(key))
            {
                (dataItem["Discontinued"].Controls[0] as CheckBox).Checked = Convert.ToBoolean(currentValues[key].ToString());
            }
        }
    }
}
