我有一个datagridview,它有一个sql查询数据。我想打印这个。请告诉我打印按钮的代码。我正在使用C#
答案 0 :(得分:1)
检查此代码可能对您有所帮助: -
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
public class Form1 :
Form
{
private Button printButton = new Button();
private PrintDocument printDocument1 = new PrintDocument();
public Form1()
{
printButton.Text = "Print Form";
printButton.Click += new EventHandler(printButton_Click);
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
this.Controls.Add(printButton);
}
void printButton_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocument1.Print();
}
Bitmap memoryImage;
private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
}
private void printDocument1_PrintPage(System.Object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}
public static void Main()
{
Application.Run(new Form1());
}
}
答案 1 :(得分:1)
以下是关于它的文章The DataGridViewPrinter Class。您可以使用此类轻松打印DataGridView。
例如,您可以在工具箱中的表单上添加PrintDocument component,在其内部的PrintPage事件中,写下:
bool more = printer.DrawDataGridView(e.Graphics);
if (more == true)
e.HasMorePages = true;
其中printer是DataGridViewPrinter对象。
要打印此文档,您可以添加按钮并将此代码添加到其单击事件中:
printer = new DataGridViewPrinter(yourGridView, printDocument1,
true, true, "title", this.Font, Color.Black, true);
if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
printDocument1.Print();
}
答案 2 :(得分:1)
这是一个很好的例子,您可以使用how to print datagrid
以下是一些代码:
private void btnPrint_Click(object sender, EventArgs e)
{
//Open the print dialog
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument1;
printDialog.UseEXDialog = true;
//Get the document
if (DialogResult.OK == printDialog.ShowDialog())
{
printDocument1.DocumentName = "Test Page Print";
printDocument1.Print();
}
/*
Note: In case you want to show the Print Preview Dialog instead of
Print Dialog then comment the above code and uncomment the following code
*/
//Open the print preview dialog
//PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
//objPPdialog.Document = printDocument1;
//objPPdialog.ShowDialog();
}