Limiting checked items of TCheckListBox on Delphi

后端 未结 1 1635
半阙折子戏
半阙折子戏 2021-01-21 07:07

I want to limit a TCheckListBox. I desire only 2 items should be checked, and all unchecked items will be disabled and grayed. Since the checked / unchecked items are dynamic, i

相关标签:
1条回答
  • 2021-01-21 07:08

    This method should do the job

    procedure DoCheckListBox( AChkLb : TCheckListBox; AMaxCheck : Integer );
    var
      LIdx : Integer;
      LCheckCount : Integer;
    begin
      // counting
      LCheckCount := 0;
      for LIdx := 0 to AChkLb.Count - 1 do
      begin
        if AChkLb.Checked[LIdx] then
          if LCheckCount = AMaxCheck then
            AChkLb.Checked[LIdx] := False
          else
            Inc( LCheckCount );
      end;
      // enable/disable
      for LIdx := 0 to AChkLb.Count - 1 do
        AChkLb.ItemEnabled[LIdx] := AChkLb.Checked[LIdx] or ( LCheckCount < AMaxCheck );
    end;
    

    UPDATE

    You better call this inside TCheckListBox.OnClickCheck event instead of OnClick event. A double-click can affect the check-state but OnClick is not called. OnClickCheck is called whenever the check-state changes.

    0 讨论(0)
提交回复
热议问题