A variation on BillWoodruff's solution that allows generalization to an arbitrary number of "rows" per "Document"
and works with the lazy behavior of
IEnumerable<T>
:
public void ProcessCheckedRows(DataGridView dgv1)
{
var allCheckedRows = dgv1.Rows
.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells[0].Value == true);
StringBuilder builder = new StringBuilder();
const int RowsPerDocument = 2;
int rowCount = 0;
foreach (var row in allCheckedRows)
{
builder.Append(ProcessRow(row));
if (++rowCount == RowsPerDocument)
{
PrintDocument(builder);
builder.Clear();
rowCount = 0;
}
}
if (rowCount > 0)
{
PrintDocument(builder);
}
}
Side note: The .Where()
looks like it could throw an exception if the Value
is null
. There's no check for .HasValue
!
Perhaps, what is wanted is:
var allCheckedRows = dgv1.Rows
.Cast<DataGridViewRow>()
.Where(row => ((bool?)row.Cells[0]).GetValueOrDefault(false));
Nevermind the Side note!
=================================================
Edit: MTH based on your updated code above, try something like:
private int currentPrintingIndex = 0;
List<string>CheckedValues = new List<string>();
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
IEnumerable<DataGridViewRow> CheckedValues = this.dgv1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells[0].Value == true)
.Skip(currentPrintingIndex);
IEnumerator<DataGridViewRow> cve = CheckedValues.GetEnumerator();
int count = 0;
int pos = 10;
while ((e.HasMorePages = cve.MoveNext()) && count++ < 2)
{
var cellValues = cve.Current.Cells.Cast<DataGridViewCell>()
.Skip(1)
.Select(cell => cell.Value.ToString())
.ToArray();
e.Graphics.DrawString(string.Join(",", cellValues), fdiag, Brushes.Black, pos, 10);
currentPrintingIndex += 1;
pos += 150;
}
}