This is pretty much how I'd do it. I'm not using a for
as the conditional checking of checkboxes is in ItemDataBound, by doing it this way the DataGrid will do all the paging for me.
Markup:
<asp:DataGrid runat="server" ID="MyDataGrid" AllowPaging="true" PageSize="10" OnPageIndexChanged="MyDataGrid_PageIndexChanged" OnItemDataBound="MyDataGrid_ItemDataBound" Autogeneratecolumns="false">
<Columns>
<asp:BoundColumn DataField="Number" HeaderText="Number" />
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox runat="server" ID="CheckBox" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable numberDataTable;
if (!IsPostBack)
{
// Build a 16-row DataTable
numberDataTable = new DataTable();
numberDataTable.Columns.Add(new DataColumn("Number"));
for (int c = 1; c < 17; c++)
{
DataRow numberDataRow = numberDataTable.NewRow();
numberDataRow[0] = c;
numberDataTable.Rows.Add(numberDataRow);
}
ViewState.Add("Data", numberDataTable);
// DataBind the table into the DataGrid
MyDataGrid.DataSource = numberDataTable;
MyDataGrid.DataBind();
}
}
protected void MyDataGrid_PageIndexChanged(object sender, DataGridPageChangedEventArgs e)
{
DataTable numberDataTable;
// Get the DataTable out of Viewstate
numberDataTable = (DataTable)ViewState["Data"];
// Set the new page number
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
// Bind the grid
MyDataGrid.DataSource = numberDataTable;
MyDataGrid.DataBind();
}
protected void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
DataRow numberDataRow;
// Selective checking of the CheckBox
// Only do this for Item and ALternatingItem, we don't do this for headers, footers etc
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
numberDataRow = ((DataRowView)e.Item.DataItem).Row;
// Check if we have an even number
if ((int.Parse(numberDataRow[0].ToString()) % 2) == 0)
{
// Find our checkbox control in the DataGrid for the current row and check it
CheckBox checkBox = (CheckBox)e.Item.FindControl("CheckBox");
checkBox.Checked = true;
}
}
}
This gives: