1

我在注释中指出的行上出现空引用异常。有谁知道为什么会这样?

var form = Form.ActiveForm as Form1;
var doSave = MessageBox.Show("Would you like to save this measurement?",
                             "Save Measurement",
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

if (doSave == DialogResult.Yes) // User wants to save the current measurement.
{
    curName = ShowDialog("Measurement Name", "Save Measurement");
    // ERROR HERE **** 
    int ret = form.databaseClass.GetFirstSoundReadyTestOccurrence(form.testNumber.Text);
4

1 回答 1

4

我敢打赌这是 Form.ActiveForm 不是 Form1 类型的情况。

这应该很容易重现。在进入此代码之前,请确保您的活动表单不是 Form1 类型。换句话说...确保在运行此代码时某些其他表单处于活动状态。

发生这种情况时,下面的编辑将修复,但您确实需要一种更可靠的方式来获取表单。如果不了解更多关于您的设计的信息,就很难推荐一种更好的获取表单的方法。

var form = Form.ActiveForm as Form1;
if (form != null)
{
var doSave = MessageBox.Show("Would you like to save this measurement?",
                             "Save Measurement",
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

if (doSave == DialogResult.Yes) // User wants to save the current measurement.
{
    curName = ShowDialog("Measurement Name", "Save Measurement");
    // ERROR HERE **** 
    int ret = form.databaseClass.GetFirstSoundReadyTestOccurrence(form.testNumber.Text);
}
}
于 2013-07-16T21:09:01.457 回答