0

What,s wrong with this code:

procedure TWinForm1.Button2_Click(sender: System.Object; e: System.EventArgs);
var varForm:TwinForm1;
begin
varForm.Close;
end;

Error: system.NullReferenceException

4
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by ttheobald
0

What,s wrong with this code:

procedure TWinForm1.Button2_Click(sender: System.Object; e: System.EventArgs);
var varForm:TwinForm1;
begin
varForm.Close;
end;

Error: system.NullReferenceException

You are closing a form that you don't create yet.
I think that the correct form is some thing like this:

var varForm:TwinForm1;
begin
  varForm := TwinForm1.Create(self);
  varForm.ShowModal;
  varForm.Close;
end;
0
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
self.Close;
end;
end.

or, if you prefer to be explicit:

procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
frmMain.Close;
end;
end.
0

What,s wrong with this code:

procedure TWinForm1.Button2_Click(sender: System.Object; e: System.EventArgs);
var varForm:TwinForm1;
begin
varForm.Close;
end;

Error: system.NullReferenceException

You are attempting to close the form from a method of the form itself - and inside the method, you are declaring a local variable and calling it "varForm" of type TwinForm1.

What's happened here is that when you call "varForm.Close", you are calling on that local variable, which doesn't have anything actually assigned to it - so you get a null reference.

If you just want to refer to a method of an object from within a method of the same object, just use "self" - it's an automatically created reference for you. In this example, use self.close and you'll be fine.

T

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.