Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

When makeing a button at runtime, how can I set the onClick event?

Status
Not open for further replies.

Kudel

Programmer
Dec 3, 2002
36
NO
Hi!

I'm creating a button at runtime and need to set it's onClick event. I've got a function named "Save" that is supposed to run when sombody click's the button.
Code:
with tbutton.Create(Form1) do
  begin;
  Parent  := Form1;
  Left    := 150;
  Top     := nyeTop;
  Caption := 'Save ' + Ticker;
  Name    := 'btn' + Ticker;
  Visible := True;
  onclick := ?????;
  end;

Kudel:)
 
OnClick := Myfunction;

MyFunction being the method you want to link to the event.
 
hi Kudel,

first you have to declare a method in the private part of your form class:
procedure MySaveButtonClick(Sender: TObject);


it's body could read:
procedure TForm1.MySaveButtonClick(Sender: TObject);
begin
Save; // or something else
end;


and then just set the OnClick of your newly created button:
OnClick := MySaveButtonClick;


this should work !

best regards
Roderich
 
Good.. now let's crank it up a notch:)

How can I tell the "Save" function which button that was clicked?
 
In your 'Click' function, you need:-

proc. MyClickthingy(Sender : TOBject);
begin
if Sender is TButton then
begin
if (Sender as TButton).name := 'btnSave'
then Save;
if (Sender as TButton).name := 'btnSomethingElse'
then doSomethingElse;
etc...
end;

Roderich, people'll think we've nothing better to do [smile2]
 
Beautiful.. and now even harder:)

While I creat the button I also creat a Edit field. The name of the button is 'btn' + the name of the edit field. My save function is supposed to save the value in edit.text when I click on the button.

I know how to save the edit.text to my db, but how can I get access to edit.text?
 
Kudel, what do you mean exactly 'get access'. Do you just need to extract the name of the edit from the button's name? If it's not that straight forward, you can associate controls by setting the .tag property, then search thru componentCount looking for associated controls.
 
Hi

I've solved it myself, but thank you for all youre help.

This is how it turned out:

Code:
procedure TForm1.MySaveButtonClick(Sender: TObject);
var
tempName: string;
RunTimeEdit : TObject;
begin
tempName := stringreplace((Sender as TButton).name,'btn','',[]);
RunTimeEdit := form1.FindComponent(TempName);
Save((runtimeedit as TEdit));
end;

Code:
procedure TForm1.Save(temp: TEdit);
begin
form1.q.SQL.Clear;
form1.q.SQL.Text := 'insert into mytable values(''' + temp.text + ''',''' + temp.name + ''')';
form1.q.ExecSQL;
end;

-Kudel:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top