【发布时间】:2021-12-15 15:02:08
【问题描述】:
我想通过单击 TButton 从 CheckListBox 中删除选中的项目,但我只找到了如何删除选定的项目,这不是我想要的。我希望你能帮助我
【问题讨论】:
我想通过单击 TButton 从 CheckListBox 中删除选中的项目,但我只找到了如何删除选定的项目,这不是我想要的。我希望你能帮助我
【问题讨论】:
此代码将执行您想要的操作。请注意,CheckBoxList1.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; 语句确保控件在我们处理其项目时不会重新绘制自身。
【讨论】:
try..finally 保护BeginUpdate..EndUpdate。
Checked[]属性getter 可以分配内存)等等。所以,不要对可以或不能发生什么做出假设。无论哪种方式,都要安全并准备好处理这两种情况。
如果我了解您的需求,请尝试以下代码:
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;
诅咒,有更好的解决方案,但它已经为你准备好了。
【讨论】:
= true 部分。 (而count 应该真的是high。)