Reputation: 2416
I want to know how to compare items between listboxes. On my main form there are two listboxes. I want to add item from 1st to 2nd with a click event but when use it, the same item will multiply on 2nd listbox. Any idea to solve "the file already exists" ?
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;
Upvotes: 1
Views: 2021
Reputation: 116110
If you got a single-select listbox1:
if Listbox2.Items.IndexOf(Listbox1.Items[Listbox1.ItemIndex]) = -1 then
begin
// Doesn't exist yet. Safe to add
end;
For multi-select (which your code seems to imply):
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]);
The latter will work for single-select too, I think.
Upvotes: 6