C# 在windows窗体应用程序中用C打印Datagrid视图
我在做库存管理系统C的一个项目时遇到了一个问题。 这里我必须用打印机打印一些带有打印按钮的datagrid视图。我在打印datagridView时遇到问题。 我有下面给出的代码。请修改代码以打印带有打印机测试的datagridview 这是我的密码:C# 在windows窗体应用程序中用C打印Datagrid视图,c#,C#,我在做库存管理系统C的一个项目时遇到了一个问题。 这里我必须用打印机打印一些带有打印按钮的datagrid视图。我在打印datagridView时遇到问题。 我有下面给出的代码。请修改代码以打印带有打印机测试的datagridview 这是我的密码: private void Print_Click(object sender, EventArgs e) { try { PrintDocument pd = new PrintDo
private void Print_Click(object sender, EventArgs e)
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1170); // all sizes are converted from mm to inches & then multiplied by 100.
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
//pd.PrinterSettings = PrinterSettings.InstalledPrinters.
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while printing", ex.ToString());
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
if (t < 1)
{
ev.Graphics.DrawString(dataGridView1., new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
t++;
if (t < 1)
{
ev.HasMorePages = true;
}
else
{
ev.HasMorePages = false;
}
}
}
这可能有助于:
我在打印方面没有那么先进,但我使用了如下打印对话框:
private void PrintDoc()
{
PrintDialog printDialog = new PrintDialog(); //make a printDialog object
PrintDocument printDocument = new PrintDocument(); // make a print doc object
printDialog.Document = printDocument; //document for printing is printDocument
printDocument.PrintPage += printDocument_PrintPage; //event handler fire
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
printDocument.Print();
}
}
如果这没有帮助,根据您的错误和代码,我不确定它所说的索引是来自dataGridView还是来自ev.graphics,但我认为您缺少一些代码
private void printDocument_PrintPage(object sender, PrintPageEventArgs ev)
{
Graphics graphic = ev.Graphics;
foreach (DataRow row in dataGridView1.Rows)
{
string text = row.ToString() //or whatever you want from the current row
graphic.DrawString(text,new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
}
}
如果你想要最简单的打印方式。试试这个:
您还可以使用它来实现更多功能。查看一下,非常感谢您的帮助。我已经尝试过了,但遇到以下问题。mscorlib.dll中发生“System.ArgumentOutOfRangeException”类型的异常,但未在用户代码中处理其他信息:索引超出范围。必须为非负数且小于集合的大小。你能帮我解决这个问题吗?我需要在哪里修改代码?提前谢谢:哪行出现异常?还有:您的DGV有多少行和多少列?在下一行中,我遇到了这个问题。如果DGV[0,行].Value!=null我有10列,行号不固定…好的,您应该使用调试器来找出失败的原因。很可能您尚未连接printDocument1_BeginPrint事件;这意味着linesPrinted仍保持在-1。因为这是每个页面上行的起点,所以它将失败。.我在中使用了代码,如果DGV[0,行],则错误在下一行中。值!=在ev.DrawString中只有Datagridview.,Datagridview中有数据吗?有。在Datagridview中有数据