I am trying to get equal number of records in both columns, even if that means that first column doesn't fill page to bottom on the second page. The only way I was able to do this was by using a maxrow count and breaking when it is equal to the max row count.
public List<DataForExcelExport> GetData()
{
var list = new List<DataForExcelExport>();
int ROWS_PER_PAGE = 41;
int MaxRow = 0;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
bool flgLastPage = false;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow dr = dataTable.Rows[i];
var item = new DataForExcelExport();
SetItemData(dr, item, true);
if (i + ROWS_PER_PAGE < dataTable.Rows.Count)
{
SetItemData(dataTable.Rows[i + ROWS_PER_PAGE], item, false);
}
list.Add(item);
if (flgLastPage == false)
{
if ((i + 1) % ROWS_PER_PAGE == 0)
{
i += ROWS_PER_PAGE;
int remaining = dataTable.Rows.Count - (i + 1);
if (remaining < 2 * ROWS_PER_PAGE)
{
ROWS_PER_PAGE = remaining / 2 + remaining % 2;
flgLastPage = true;
}
}
}
int maxrow = i + ROWS_PER_PAGE;
if (maxrow == dataTable.Rows.Count)
{
break;
}
}
return list;
}
expected output: when there are a total of 118 rows
- page 1
_________
1 | 41
... |...
38 | 78
39 | 79
40 | 80
_________
- page 2
_________
81 | 99
82 | 100
... | ...
98 |118
_________
dataTable.Rows.Count
andROWS_PER_PAGE
you can calculate the number of pages, and number of rows on the given page in advance, then process things with 2 loops. One for pages, one for rows \$\endgroup\$ – jakubiszon Nov 1 '19 at 15:57