Jump to content
Shrinavat

How to check if parent menu item has "checked" child item?

Recommended Posts

Hi,

How to correctly check if the parent menu item has at least one child item with Checked = True?

Is it good way?

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  i: integer;
begin
  Result := False;
  for i := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[i].Checked then
      Exit(True);
end

I'd appreciate any help you can give me. Thank you.

Edited by Shrinavat
solved?

Share this post


Link to post

Looks good. I wouldn't mix result with exit(..), but that's probably a matter of taste.

  • Thanks 1

Share this post


Link to post
On 12/25/2018 at 4:45 PM, dummzeuch said:

Looks good. I wouldn't mix result with exit(..), but that's probably a matter of taste.

The compiler encourages that mix, as it warns of the Result not having been initialized otherwise.

  • Thanks 1

Share this post


Link to post

The following

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  Result := False;
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
    begin
      Result := True;
      Exit;
    end;
end;

produces no warnings, no hints for me with 10.3 Tokyo.

  • Thanks 1

Share this post


Link to post
On 12/30/2018 at 1:35 PM, Ondrej Kelle said:

produces no warnings, no hints for me with 10.3 Tokyo.

I meant 10.3 Rio, sorry. 🙂

Share this post


Link to post
On 12/30/2018 at 1:35 PM, Ondrej Kelle said:

The following


function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  Result := False;
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
    begin
      Result := True;
      Exit;
    end;
end;

produces no warnings, no hints for me with 10.3 Rio.

Yes, but it does not use Exit(True) any  more but requires an additional line:

Result := True;
Exit;

And of course the begin / end block to allow for two statements.

 

This would be my preferred solution:

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
      Exit(True);
  Exit(False); 
end;

(But I rarely use any Delphi version that supports Exit() with a return value.)

  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×