グリッドビューまたはリピーター コントロールの場合は、これを試してください
グリッドビュー HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True"
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CSコード
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridView1.PageIndex = e.NewPageIndex;
BindData();
RePopulateValues();
}
と
private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int) GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;
// Check in the Session
if (Session[CHECKED_ITEMS] != null)
categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session[CHECKED_ITEMS] = categoryIDList;
}
と
private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
myCheckBox.Checked = true;
}
}
}
}
バインド データ コード
編集
/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(QUERY_SELECT_ALL_CATEGORIES,
myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
詳細については、このMaintaining_State_of_CheckBoxesを確認してください