Re: Combining code

Posted by John, DelphiLand Team on February 15, 2007

In Reply to Combining code posted by Graham J Hadlington p12555 on February 14, 2007

If I write say, edit1.enabled :=true and needed this for say, 20 editboxes, how can I combine the code instead of typing it (or copy and paste) 20 times?

It's possible, as is shown in the example in our article Code Snips: Changing properties for all components of a certain type :

for i := 0 to ComponentCount - 1 do
  if Components[i] is TEdit then 
    TEdit(Components[i]).Enabled := False;

Instead of changing all of the edit boxes, you can easily limit this to edit boxes that comply to a condition, by adding a condition to the "if" statement. For example: located in a certain container (such as a panel, groupbox,...), within certain coordinates on the screen, all the edit boxes minus a few, and so on. Here are a few source code examples:

Edit boxes located on Panel1:

  if (Components[i] is TEdit)   
      and (TEdit(Components[i]).Parent = Panel1) then 

Edit boxes Located on the left of the page:

  ... and (TEdit(Components[i]).Left < 30) then

All edit boxes except Edit1 and Edit2:

  ... and (TEdit(Components[i]) <> Edit1) 
      and (TEdit(Components[i]) <> Edit2) then

The possibilities are endless. Personally I prefer the first example, because that makes it easier to update the code. Note that you can optically hide the panel by changing its borders in the Object Inspector. Note also that you could use more panels, such as:

 if (Components[i] is TEdit) 
    and ((TEdit(Components[i]).Parent = Panel1)
         or (TEdit(Components[i]).Parent = Panel2)) then 

John, DelphiLand Team

Related articles

       

Follow Ups