【问题标题】:How to print a single row of DataGridView如何打印单行DataGridView
【发布时间】:2015-09-08 13:48:40
【问题描述】:

大家好,我已经寻找这个帮助好几个星期了,但还没有得到答案 我走了...我有一个 datagridview ,这个 DGV 有一个名为 ("print") 的 ColumnCheckBox 和其他 3 列是 (Number,Description,Price) 当我通过单击 ColumnCheckBox("Print") 选择一行时,我想从提到的这 3 列中获取该行的值。通过单击打印按钮,它将仅打印其中的每一行!伙计们,我所有的搜索都运行以创建一个数组,然后从数组中打印出来,但我不知道怎么做!

每一个答案都将得到尝试和赞赏

【问题讨论】:

  • 一开始都是如何从选中的行中获取值并设置为数组或列表,之后如何循环所有得到的值并打印出来!

标签: c# .net winforms printing datagridview


【解决方案1】:

这样您可以使用某些条件找到一行,例如您可以找到您的第一个选中行:

var firstCheckedRow = this.myDataGridView.Rows.Cast<DataGridViewRow>()
                          .Where(row => (bool?)row.Cells["MyCheckBoxColumn"].Value == true)
                          .FirstOrDefault();

这样你可以得到一行所有单元格的值,例如你可以把主题放在不同行的字符串中:

var builder = new StringBuilder();
firstCheckedRow.Cells.Cast<DataGridViewCell>()
               .ToList().ForEach(cell =>
               {
                   builder.AppendLine(string.Format("{0}", cell.Value));
               });

然后你可以展示他们:

MessageBox.Show(builder.ToString());

甚至您也可以在表单上添加PrintDocument 并处理PrintPage 事件以将它们打印到打印机。您还应该在表单上放置一个Button,并在按钮的单击事件中调用PrintDocument1.Print();

代码:

private void Button1_Click(object sender, EventArgs e)
{
    PrintDocument1.Print();
}

PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    var firstCheckedRow = this.myDataGridView.Rows.Cast<DataGridViewRow>()
                              .Where(row => (bool?)row.Cells["MyCheckBoxColumn"].Value == true)
                              .FirstOrDefault();
    var builder = new StringBuilder();
    firstCheckedRow.Cells.Cast<DataGridViewCell>()
                   .ToList().ForEach(cell =>
                   {
                       builder.AppendLine(string.Format("{0}", cell.Value));
                   });

    e.Graphics.DrawString(builder.ToString(),
               this.myDataGridView.Font,
               new SolidBrush(this.myDataGridView.ForeColor),
               new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
}

【讨论】:

  • 嗨 Reza Aghaei 你的代码对我的项目太有用了!谢谢!但我仍然需要用另一个标准来完成!我会提出一个新问题并在此处标记您或在此处发布链接!谢谢你!
  • 看看答案是否被投票!我注意到我需要有一些声誉分数才能公开投票!我想!顺便问一下,你有一些电子邮件联系方式吗?
  • 这是我的另一个问题 Reza Aghaei 打印 - 如何在 c# 中仅打印来自 datagridview 的检查行 - 代码日志stackoverflow.com/questions/32485741/…
猜你喜欢
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
相关资源
最近更新 更多