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

Member Avatar for Micheus

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;
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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.