值不能为null Windows窗体C#中的异常

时间:2012-05-16 07:59:10

标签: c# .net winforms visual-studio-2010

我正在使用Windows窗体创建员工卡布局。除此之外,我还添加了一个名为“Print”的按钮,它将打印面板内容。当我运行代码它在窗体加载时显示错误: Form Error

这是我的代码:

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 Event的第一行崩溃了。 请帮帮我。

2 个答案:

答案 0 :(得分:3)

MemoryImage在调用GetPrintArea()之前为空。

试试这个:

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

仅当你不想在它为空时绘制它时。因为它最初为null,然后您在GetPrintArea()中设置它。根据您的情况,您可以调用GetPrintArea()而不是null检查,或者您可以立即初始化MemoryImage,这一切都取决于您希望它如何工作。

答案 1 :(得分:0)

你永远不会设置你的MemoryImage。在printpage事件中,在调用DrawImage之前添加GetPrintArea(pnl)