我在我用评论指出的行上得到了一个空引用异常。有没有人知道为什么会这样?
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);
答案 0 :(得分: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);
}
}