I have datagrid with paging enabled that can have 10 rows per page. Also I have DataTable with 16 rows. I want to fill the datagrid dynamically with 'for' loop to go over all the DataTable and fill the DataGrid.
I understand that there is a problem when the counter will hit row 11. Do I need to change the page of the datagrid when counter will be 11? Because it doesnt let me add more than 10 rows in the datagrid.
Would appriciate if someone can tell me how to implement it.
Thanks in advance,
Greg
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: