Reputation: 1055
please help me, i am new about Delphi. I need to generate textbox dynamically like
text[1]
text[2]
...
text[n]
And i can also retrieve their value maybe like this (example),
for (i=1; i<=n; i++)
arrayOfTxt[i] = text[i].text;
Is it possible on Delphi? if it is possible, then how to do that?
Upvotes: 0
Views: 2806
Reputation: 8261
To answer your stated question: Yes, it is possible.
To elaborate: Delphi has what's called Dynamic Arrays, where you don't specify the boundaries of the index at compile-time, but only at run-time.
So a function to create a user-supplied number of edit boxes (TEdit) could be like this:
TYPE
TEditArr = ARRAY OF TEdit;
FUNCTION MakeEditBoxes(ParentForm : TForm ; Count : Cardinal) : TEditArr;
VAR
I : Cardinal;
BEGIN
SetLength(Result,Count);
FOR I:=1 TO Count DO BEGIN
Result[PRED(I)]:=TEdit.Create(ParentForm);
Result[PRED(I)].Parent:=Parent
END
END;
You would use it something like this:
Place the following line in your form's class declaration:
Edits : TEditArr;
Then create the boxes like this:
PROCEDURE TForm1.Button1Click(Sender : TObject);
VAR
E : TEdit;
Y : Cardinal;
BEGIN
Edits:=MakeEditBoxes(Self,20);
Y:=0;
FOR E IN Edits DO BEGIN
E.Top:=Y; E.Left:=0;
INC(Y,E.Height+8)
END
END;
To access their texts, you can use something like this (assuming you want to copy all their texts to a single mulit-line edit box (TMemo) on your form):
.
.
.
VAR E : TEdit;
.
Memo1.Lines.Clear;
FOR E IN Edits DO Memo1.Lines.Add(E.Text);
.
.
.
or - if you want to access them by index:
.
.
.
VAR I : Integer;
.
Memo1.Lines.Clear;
FOR I:=LOW(Edits) TO HIGH(Edits) DO Memo1.Lines.Add(Edits[I].Text);
.
.
.
If you want the text of a specific edit box (f.ex. the 3rd one), you'd use
Edits[2].Text
remembering that dynamic arrays always start their index at 0 (but if you want to loop around all indexes, use LOW and HIGH as that's what they are there for, and it'll make it clear what you are doing to anyone reading your code, even though they may or may not be familiar with Delphi). Note how I only specify the count of edit boxes at ONE place in my code, and if I want to have a different number, it'll only be that one place that I have to alter - all the remaining code will automatically adapt to the correct number without modifications.
Upvotes: 3