Limiting checked items of TCheckListBox on Delphi

依然范特西╮ 提交于 2019-12-02 01:14:39

问题


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 can not use a static itemIndex.

Here is what i tried, but i got "Out of chip bounds" error.

On click event of my CheckListBox ;

var
  NumberOfCheckedItems, I: Integer;
begin
  NumberOfCheckedItems := 0;
  for I := 0 to CkLst1.Count - 1 do
  begin
    if CkLst1.Checked[I] then
      NumberOfCheckedItems := NumberOfCheckedItems + 1;
  end;
  if NumberOfCheckedItems > 1 then
  begin
    CkLst1.Checked[I] := Enabled;
    CkLst1.Enabled := FALSE;
    CkLst1.AllowGrayed := TRUE;
  end
  else
  begin
    //no idea
  end;
end;

回答1:


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.



来源:https://stackoverflow.com/questions/23237636/limiting-checked-items-of-tchecklistbox-on-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!