我正在使用Windows窗體創建員工卡布局。除此之外,我還添加了一個名爲「打印」的按鈕,它將打印面板內容。當我運行的代碼,它顯示錯誤時,窗體加載: 值不能爲空在Windows窗體C中的異常#
這裏是我的代碼:
namespace SimpleReport
{
public partial class EmployeeCardForm : Form
{
//Declare following Object Variables
PrintDocument printdoc1 = new PrintDocument();
PrintPreviewDialog previewdlg = new PrintPreviewDialog();
Panel pannel = null;
public EmployeeCardForm()
{
InitializeComponent();
//declare event handler for printing in constructor
printdoc1.PrintPage += new PrintPageEventHandler(printdoc1_PrintPage);
}
Bitmap MemoryImage;
public void GetPrintArea(Panel pnl)
{
MemoryImage = new Bitmap(pnl.Width, pnl.Height);
Rectangle rect = new Rectangle(0, 0, pnl.Width, pnl.Height);
pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, pnl.Width, pnl.Height));
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(MemoryImage, 0, 0);
base.OnPaint(e);
}
void printdoc1_PrintPage(object sender, PrintPageEventArgs e)
{
Rectangle pagearea = e.PageBounds;
e.Graphics.DrawImage(MemoryImage, (pagearea.Width/2) - (this.panel1.Width/2), this.panel1.Location.Y);
}
public void Print(Panel pnl)
{
pannel = pnl;
GetPrintArea(pnl);
previewdlg.Document = printdoc1;
previewdlg.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
Print(this.panel1);
}
}
}
當我調試我才知道,它崩潰的OnPaint事件的第一行代碼。 請幫我一把。
好吧,你說'位圖MemoryImage'並且它發生在你點擊的時候paint事件激發了很久,'MemoryImage'在那個點上應該是null。 – V4Vendetta