Solve NullReference exception

2019-09-05 06:06发布

问题:

I use crystal report to implement reporting in my c# windows application.I create a form to show print preview of Report.I use following code to show preview:

private ReportDocument _reportDocument;
public CrystalReportPrintPreviewForm(ReportDocument reportDocument)
{
    InitializeComponent();

    _reportDocument = reportDocument;
}
private void CrystalReportPrintPreviewForm_Load(object sender, EventArgs e)
{
    if(_reportDocument!=null)
    crystalReportViewer1.ReportSource = _reportDocument;
}

And also i use following code to send 'ReportDocument' to this form and show it:

ReportDocument reportDocument = new ReportDocument();
reportDocument.Load(Application.StartupPath + "\\Reports\\WorkGroupReport.rpt");
kargarBandarDataset.WorkGroup.DefaultView.RowFilter = workGroupBindingSource.Filter;
reportDocument.SetDataSource(kargarBandarDataset.WorkGroup.DefaultView.ToTable());
reportDocument.SetParameterValue("CurrentDate",shamsi.ShamsiDate());

CrystalReportPrintPreviewForm crystalReportPrintPreview = new CrystalReportPrintPreviewForm(reportDocument);
crystalReportPrintPreview.ShowDialog();

Sometimes I get NullReferenceException error message in the following line of Code:

crystalReportPrintPreview.ShowDialog();

How Can i solve this problem?

回答1:

There is no exact answer of how to handle NullReferenceException. Make sure that you enabled "cathching" of thrown expections in VS (Debug->Exception mark Common Language Runtime) find the place where expection if thrown and try to undestand the reasons.

Also, try to get as much more information from .Message property of Exception.

Typically NullReference caused by some null arguments submitting to method or constructor of class. Try to debug and see what you passing to object that throws an exception;



回答2:

Are you sure that crytsalReportPrintPreview was created? If the line

crystalReportPrintPreview.ShowDialog();

is the line actually throwing the error, the NullReference Exception would seem to be indicating that crystalReportPrintPreview is null.

Another thing to check is whether or not reportDocument is null - perhaps the DataSource is null for some reason). I'd add the following to your code:

if (reportDocument == null)
{
    throw new Exception("reportDocument is null!");
}
else
{
    // put your CrsytalReportPrintPreviewForm code here
}


回答3:

Like a first step i would suggest to insure that you have Exceptions handling enabled in VS.

Don't have PC on my hands, but it have to be something like:

Debug->Exceptions

Appears diaolog where you can check exceptions you're interested in. If this doesn't work you can try way suggested by @Marlyn

Hope this helps.



回答4:

I'm suspicious of your parameter code:

reportDocument.SetParameterValue("CurrentDate",shamsi.ShamsiDate);

If the parameter corresponds to a date with no data, then that might be the source of your null.