2012-05-16 21 views
1

我正在使用Windows窗體創建員工卡布局。除此之外,我還添加了一個名爲「打印」的按鈕,它將打印面板內容。當我運行的代碼,它顯示錯誤時,窗體加載: Form Error值不能爲空在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事件的第一行代碼。 請幫我一把。

+0

好吧,你說'位圖MemoryImage'並且它發生在你點擊的時候paint事件激發了很久,'MemoryImage'在那個點上應該是null。 – V4Vendetta

回答

3

MemoryImage在調用GetPrintArea()之前爲空。

試試這個:

protected override void OnPaint(PaintEventArgs e) 
{ 
    if (MemoryImage != null) 
    { 
     e.Graphics.DrawImage(MemoryImage, 0, 0); 
    } 
    base.OnPaint(e); 
} 

這只是如果你不想畫它時,它是空的。由於它最初爲空,因此您將其設置爲GetPrintArea()。根據您的情況,您可以調用GetPrintArea()而不是空檢查,也可以立即初始化MemoryImage,這完全取決於您希望如何工作。

+0

它工作。非常感謝你!!! – Azeem

+0

不用擔心,只要在MemoryImage爲空時絕對是你想要做的。 – ThePower

0

你從來沒有設置你的MemoryImage。在您的printpage事件中,在調用DrawImage之前,添加GetPrintArea(pnl)

+0

沒有工作! – Azeem

+0

你是否通過代碼來確保自己的MemoryImage是按照預期創建的? – riffnl

相關問題