Hasan A.
Hasan A.

Reputation: 23

Controlling multiple TEdits as array

I am trying to programme a Sudoku solver, and I want to control 81 TEdit controls as array, but their names are Edit1, Edit2, Edit3 instead of Edit[1], Edit[2], etc.

I do not want to type OnChange event handlers for all 81 controls separately.

How can I solve this?

Upvotes: 2

Views: 1791

Answers (4)

NGLN
NGLN

Reputation: 43669

In addition to the use of a common OnChange event handler and creating the edits runtime, you could also fill an array with designtime made controls.

As I recently explained in this answer, you can add designtime made controls to your one- or two-dimensional array: by searching them on name with FindComponent, searching them on Tag property with a loop, or by manually adding them to the array by typing their 81 variables.

Upvotes: 2

Toon Krijthe
Toon Krijthe

Reputation: 53406

You can create the edits dynamically.

Be sure to set the owner and the parent of the edit boxes.

procedure TForm1.OnCreate(Sender: TObject);
var
  x, y : Integer;
begin
  for y := 1 to 9 do begin
    for x := 1 to 9 do begin
      FEdit[x,y] := TEdit.Create(self);
      FEdit[x,y].Parent := self;
      FEdit[x,y].Left :=   // function based on x
      FEdit[x,y].Top  :=   // function based on y
      FEdit[x,y].Name :=   // function based on x and y
      FEdit[x,y].Width     //  any value you like
      FEdit[x,y].Height    // any value you like
      FEdit[x,y].Tag = 10*y + x;
      FEdit[x,y].OnChange = OnHandleChange;
    end;
  end;
end;

procedure TForm1.OnHandleChange(Sender: TObject);
var
  x,y : Integer;
begin
  if not Sender is TEdit then Exit;
  y := TEdit(Sender).Tag div 10;
  x := TEdit(Sender).Tag mod 10;
  // Add check if x and y are valid  

 // You now know that FEdit[x,y] is changed and you can handle accordingly.
end;

FEdit is a two dimensional array field of the form.

Upvotes: 5

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

You can do something like this:

var
  myedit: array[1..81] of TEdit;
  i: integer;
...
begin
...
for i := 1 to 81 do begin
  myedit[i] := TEdit.Create(form1);
  with myedit[i] do begin
    width := 50;
    top := 50 + (i * 55);
    left := 50;
    text := 'mytext '+inttostr(i);
    parent := form1;
    // more properties...
    end;
  end;
...

You can create whatever you want dynamically, using similar code.

Upvotes: 2

Marjan Venema
Marjan Venema

Reputation: 19356

You don't need to do it one by one. You can select multiple controls on a form using shft-click or ctrl-drag to select them by a rectangle.

So in general:

  • Use the Object Inspector to set up the OnChange handler for one Edit
  • Optionally rename it to a more general name using the Object Inspector
  • Select all other edits on the form
  • Select the handler you just created using the Object Inspector. It will be assigned to all edits you selected.

Upvotes: 6

Related Questions