列表框删除新添加的现有内容

时间:2016-06-25 17:55:36

标签: delphi

打开opendialog multiselect选项后,我添加了文件:

procedure TForm2.cxButton2Click(Sender: TObject); //add files
begin
if OpenDialog1.Execute then
    ListBox1.Items.Assign(OpenDialog1.Files);
end;

但是,如果我想再追加一个文件,添加会删除列表框中列出的上一个列表。这可能是设计但是你如何克服这个?

另外,有没有办法可以避免添加重复的条目?

1 个答案:

答案 0 :(得分:5)

TStrings.Assign用新内容替换任何内容。它没有添加。

要添加单个项目,请使用Add

if OpenDialog1.Execute then
  ListBox1.Items.Add(OpenDialog1.FileName);

使用AddStrings一次添加多个项目,同时保留已经存在的内容:

if OpenDialog1.Execute then
  ListBox1.Items.AddStrings(OpenDialog1.Files);

不幸的是, TListBoxItems 没有TStringList的Duplicates属性,因此没有简单的方法来防止重复。如果您一次只添加一个新项目,则可以手动检查它是否已经存在。

if OpenDialog1.Execute then
  if ListBox1.Items.IndexOf(OpenDialog1.FileName) = -1 then
    ListBox1.Items.Add(OpenDialog1.FileName);

如果您要添加多个项目并希望避免重复,则可以使用中间TStringList;但是,它会产生(可能不需要的)排序项目的副作用。

var
  SL: TStringList;
begin
  if OpenDialog1.Execute then
  begin
    SL := TStringList.Create;
    ListBox1.Items.BeginUpdate;
    try
      SL.Sorted := True;   // Required in order to use Duplicates
      SL.Duplicates := dupIgnore;
      SL.Assign(ListBox1.Items);
      SL.AddStrings(OpenDialog1.Files);
      ListBox1.Items.Assign(SL);
    finally
      SL.Free;
      ListBox1.Items.EndUpdate;
    end;
  end;
end;