NullReferenceException

  • Thread starter Thread starter Scott Toney
  • Start date Start date
S

Scott Toney

I am navigating thru multiple forms. Prior to going into each form, I am :
frmTest.Close()
frmTest = nothing
But on one form, I am getting a :
nullreferenceexception on frmTest.Dispose()
 
if the reference equals to null, it's normal that the dispose method fails
(because it is called on a null object).

take a look at the using statement :

using(frmMain f = new frmMain())
{
f.ShowDialog();
}

If you need navigate throught multiple forms, I suggest you to have a main
form (or a console application why not) that have a method display form.
Each time the user request a form, close the current window, dispose it and
then open the newly requested form...

ex:

class frmmain : Form
{
private BaseForm _currentForm;

public void SetCurrentForm(Type formType)
{
_currentform.Close();
_currentForm.dispose();
_currentform = (BaseForm)Activator.CreateInstance(formType, this);
_currentForm.ShowDialog();
}
}

class BaseForm : BaseForm
{
protected frmmain _mainForm;

public BaseForm(frmmain mainform)
{
_mainForm = mainform;
}

}

class Form1 : Baseform
{
public Form1(frmmain mainform) : base(mainform)
{
}
private void button1_Click(object sender, EventArgs e)
{
_mainForm.SetCurrentForm(typeof(Form2));
}
}

Steve
 
I am doing something along that line.
MainForm
Private Sub miTests_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles miTests.Click
CloseWorkingForm(sender, e)
WorkingForm = "fForm"
fForm = New frmSubdivision
fForm.ShowDialog()
End Sub

Private Sub CloseWorkingForm(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Select Case WorkingForm
Case "fForm"
If (Not fForm Is Nothing) Then
fForm.Close()
fForm = Nothing
End If
End Select
End Sub

The application runs thru the closeworkingform and "closes" the form. The
nullreference comes when I hit application.Exit.
 
Also, on my "Application Exit" menu item, I have :
if (not fForm is nothing) then
messagebox.show("A")
fForm.Close()
fForm = nothing
end if
and I don't get the message, but I still get the
NullReferenceException

at ND.fForm.Dispose()
at
System.ComponentModel.Component.Finalize()
 
since the variable fForm is null... call to fForm.Dispose() will hangs !
Do not start your application on a form that you set to null.
You can have a form that is not shown to the user but only help navigate
trough other form. When application.Exit, it will dispose this form.

Steve
 
Back
Top