Delphi项目比较2个列表框

Ste*_*e88 1 delphi delphi-5

我想知道如何比较列表框之间的项目.在我的主表单上有两个列表框.我想通过点击事件将项目从第1个添加到第2个,但是当使用它时,相同的项目将在第2个列表框中相乘.任何想法解决"文件已存在"

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
begin
  for i := ListBox1.Items.Count - 1 downto 0 do
    if ListBox1.Selected[i] then                       
      ListBox2.Items.Add(ListBox1.Items.Strings[i]);
end;
Run Code Online (Sandbox Code Playgroud)

Gol*_*rol 5

如果你有一个选择listbox1:

if Listbox2.Items.IndexOf(Listbox1.Items[Listbox1.ItemIndex]) = -1 then
begin
  // Doesn't exist yet. Safe to add
end;
Run Code Online (Sandbox Code Playgroud)

对于多选(您的代码似乎暗示):

for i := 0 to ListBox1.Items.Count - 1 do
  if (ListBox1.Selected[i] and (ListBox2.Items.IndexOf(ListBox1.Items[i]) = -1) then                       
    ListBox2.Items.Add(ListBox1.Items[i]);
Run Code Online (Sandbox Code Playgroud)

我认为后者也适用于单选.