从 CheckListBox 中删除选中的项目

问题描述 投票:0回答:2

我想通过单击 TButton 从 CheckListBox 中删除选中的项目,但我只找到了如何删除所选项目,这不是我要找的。我希望你能帮助我

delphi delphi-10.1-berlin
2个回答
3
投票

此代码将执行您想要的操作。请注意,每次删除项目时,

CheckListBox1.Items.Count
都会减一。因此,我们在 for 循环中使用
downto
而不是
do

procedure TForm1.Button1Click(Sender: TObject);
var
  index: Integer;
begin
  CheckListBox1.Items.BeginUpdate;
  try
    for index := (CheckListBox1.Items.Count - 1) downto 0 do
      if (CheckListBox1.Checked[index]) then
        CheckListBox1.Items.Delete(index);
  finally
    CheckListBox1.Items.EndUpdate;
  end;
end;

CheckListBox1.Items.BeginUpdate;
CheckListBox1.Items.EndUpdate;
语句确保控件在我们处理其项目时不会重新绘制自身。


0
投票

如果我明白你需要什么,请尝试以下代码:

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
  count : Integer;
begin
  i:= 0;
  count :=   CheckListBox1.Items.Count - 1;
  while i <= count  do
       if CheckListBox1.Checked[i] = true then
       begin
               CheckListBox1.Items.Delete(i);
               count := count - 1;
       end else i:=i+1;
end;

当然,还有更好的解决方案,但它已准备好供您使用。

© www.soinside.com 2019 - 2024. All rights reserved.