Thursday 13 September 2012

Maintaining State of CheckBoxes While Paging in a GridView Control

 Here I User server side events for maintain checkbox state.


protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

SaveCheckedValues();

gvdetails.PageIndex = e.NewPageIndex;

BindGridData();

PopulateCheckedValues();

}

//This method is used to populate the saved checkbox values

private void PopulateCheckedValues()

{

ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];

if (userdetails != null && userdetails.Count > 0)

{

foreach (GridViewRow gvrow in gvdetails.Rows)

{

int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

if (userdetails.Contains(index))

{

CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");

myCheckBox.Checked = true;

}

}

}

}

//This method is used to save the checkedstate of values

private void SaveCheckedValues()

{

ArrayList userdetails = new ArrayList();

int index = -1;

foreach (GridViewRow gvrow in gvdetails.Rows)

{

index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;

// Check in the Session

if (Session["CHECKED_ITEMS"] != null)

userdetails = (ArrayList)Session["CHECKED_ITEMS"];

if (result)

{

if (!userdetails.Contains(index))

userdetails.Add(index);

}

else

userdetails.Remove(index);

}

if (userdetails != null && userdetails.Count > 0)

Session["CHECKED_ITEMS"] = userdetails;

}

No comments:

Post a Comment