这是一个使用List<string> 完成您需要的代码,您可以简单地使用List<DataGridViewRow> 而不是List<string>:
List<string> CheckedValues = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
CheckedValues = new List<string> { "value1", "value2", "value5", "value8", "value10", "value11" };
printDocument1.Print();
}
int currentPrintingIndex = 0;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//Width of output labels
var d= this.printDocument1.DefaultPageSettings.PrintableArea.Width / 2;
//Print first output label
if (CheckedValues.Count > currentPrintingIndex)
{
var currentValue = CheckedValues[currentPrintingIndex];
e.Graphics.DrawString(currentValue.ToString(),
this.Font,
new SolidBrush(this.ForeColor),
new RectangleF(
0,
0,
d,
this.printDocument1.DefaultPageSettings.PrintableArea.Height));
currentPrintingIndex += 1;
}
//Print second output label
if (CheckedValues.Count > currentPrintingIndex)
{
var currentValue = CheckedValues[currentPrintingIndex];
e.Graphics.DrawString(currentValue.ToString(),
this.Font,
new SolidBrush(this.ForeColor),
new RectangleF(
d,
0,
d,
this.printDocument1.DefaultPageSettings.PrintableArea.Height));
currentPrintingIndex += 1;
}
//If there is more item to print, go to next page
e.HasMorePages = CheckedValues.Count > currentPrintingIndex;
}
输出将是:
Page 1
value 1 value 2
Page 2
value 5 value 8
Page 3
value 10 value 11
这背后的逻辑很简单。我们想在 2 个输出列中显示数据。所以我们应该检查我们是否不在 Checked Cells List 的末尾,打印第一行,然后再次检查我们是否不在 Checked Cells List 的末尾打印第二行,然后检查选中的单元格列表中是否有更多项目,所以我们说使用e.HasMorePages = CheckedValues.Count > currentPrintingIndex; 转到下一页并将打印指针移动到下一个选中的单元格。
编辑
这里是 Elton Joani 编辑的终极解决方案
private int currentPrintingIndex = 0;
List<string> CheckedValues = new List<string>();
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//Barcode Font
Font fbarra = new Font("IDAutomationSC128S", 10, FontStyle.Regular, GraphicsUnit.Pixel);
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 = 60;
while ((e.HasMorePages = cve.MoveNext()) && count++ < 2)
{
var cellValues = cve.Current.Cells.Cast<DataGridViewCell>()
.Skip(1) //instead of .Where(cell => cell.ColumnIndex > 0)
.Select(cell => cell.Value.ToString())
.ToArray();
StringBuilder builder = new StringBuilder();
builder.Append(string.Join(",", cellValues));
string fullline = builder.ToString();
string[] column1 = fullline.Split(',');
var cents = column1[3].Substring(0, 2);
var descr = column1[1].ToString();
var descr2 = descr.Substring(0, 30);
var descr3 = descr.Substring(30);
var encodeddata1 = Encode.Code128(column1[0].ToString(), 0, false);
var number = encodeddata1;
//draw barcode
e.Graphics.DrawString(number, fbarra, Brushes.Black, pos, 105);
currentPrintingIndex += 1;
pos += 150;
}
}