Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter when creating a new form in delphi SDI

Ok, I'm sorry if this is a little bit confusing but I don't know how to explain it better. I have a chat form that is shown after the user has previously authenticated in TLoginForm.

User logged in then show the chatForm:

with TChatForm.Create(Application) do
begin
    Show;
end;

My problem is , how can I pass the username to the chatForm so I can use it as nickname in the chat, considering the fact that the form automatically connects to server OnShow, so I'll be needing the username sent already.

I'm new to delphi so if there's any mistake in my code, kindly excuse me.

like image 478
Eduard Avatar asked Dec 25 '12 18:12

Eduard


2 Answers

If the username should be fixed during the entire lifetime of the object then it should be passed in to the constructor. The benefit is that it's not possible to misuse the class and forget to assign the username.

Declare a constructor that receives the extra information in parameters:

type
  TMyForm = class(TForm)
  private
    FUserName: string;
  public
    constructor Create(AOwner: TComponent; 
        const UserName: string);
  end;

constructor TMyForm.Create(AOwner: TComponent; 
        const UserName: string);
begin
  inherited Create(AOwner);
  FUserName := UserName;
end;

Create the form like this:

MyForm := TMyForm.Create(Application, UserName);
like image 193
David Heffernan Avatar answered Nov 11 '22 20:11

David Heffernan


Add a public method to your chatform.

with TChatForm.Create(Application) do
begin
  PassUserName(FUsername);
  Show;
end;

procedure TChatForm.PassUserName(const aUsername: string);
begin
  Caption := 'You can now chat: '+ aUsername;
end;

This allows you to pass whatever you want into your Chat Form without changing existing public methods by simply adding new ones.
Example without using "with" or FUsername to address concerns:

frmChat := TChatForm.Create(Application);
frmChat.Nickname := aUsername;
frmChat.Show;

TChatForm = class(TForm)
private
  FUsername : string;

  procedure SetNickName(const Value: string);
  function GetNickName: string;
public
  property NickName: string read GetNickName write SetNickName;
end;

procedure TChatForm.SetNickName(const Value: string);
begin
  FUsername := Value;
end;
function TChatForm.GetNickName: string;
begin
  Result := FUsername;
end;
like image 37
SteB Avatar answered Nov 11 '22 19:11

SteB