Brad
Brad

Reputation: 2237

How can a list box disallow duplicate items?

I was looking at http://delphi.about.com/od/tlistbox/a/list-box-onchange-drag-drop.htm and I was wondering if it would be possible to add the ability to disallow duplicate items like this, and if so how would I go and do it?

Thanks

-Brad

Upvotes: 1

Views: 4740

Answers (2)

pwalkz
pwalkz

Reputation: 11

I often use;

var
  item1 : string;
begin
  item1 := Trim(eSym1.Text);
  if ListBox1.Items.IndexOf(item1) < 0 then
    ListBox1.Items.Add(item1);
end; 

Upvotes: 1

Rob Kennedy
Rob Kennedy

Reputation: 163357

To prevent duplicates in a list box, simply check whether the intended item exists in the list before you add it.

function ItemExists(ListBox: TListBox; const Item: string): Boolean;
begin
  Result := ListBox.Items.IndexOf(Item) >= 0;
end;

Call that function before you call Items.Add. If it returns True, don't call Items.Add.

Upvotes: 7

Related Questions