Saturday, June 11, 2011

Maintaining State of CheckBoxes While Paging in a GridView Control

CREATE THIS AS GLOBAL

public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex";

private void RePopulateCheckBoxes()
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;

IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;

if (SelectedCustomersIndex != null)
{
if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
{
chkBox.Checked = true;
}
}
}
}

private List SelectedCustomersIndex
{
get
{
if (ViewState[SELECTED_CUSTOMERS_INDEX] == null)
{
ViewState[SELECTED_CUSTOMERS_INDEX] = new List();
}

return (List)ViewState[SELECTED_CUSTOMERS_INDEX];
}
}

private void RemoveRowIndex(int index)
{
SelectedCustomersIndex.Remove(index);
}

private void PersistRowIndex(int index)
{
if (!SelectedCustomersIndex.Exists(i => i == index))
{
SelectedCustomersIndex.Add(index);
}
}


WRITE THIS IN GRIDVIEW PAGEINDEXCHANGING

protected void grdInvitee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;

IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;

if (chkBox.Checked)
{
PersistRowIndex(container.DataItemIndex);
}
else
{
RemoveRowIndex(container.DataItemIndex);
}
}

grdInvitee.PageIndex = e.NewPageIndex;
PopulateInviteeGrid();
RePopulateCheckBoxes();

}

No comments:

Post a Comment