Re: Delphi TStringList not allowing duplicates


[ Related Articles and Replies ] [ DelphiLand Discussion Forum ]

Posted by webmaster Guido on February 05, 2002 at 19:14:48:

In Reply to: Delphi TStringList not allowing duplicates posted by BeckyR on February 05, 2002 at 15:22:02:

: How do I use the duplicates property to raise an exception when a duplicate string is added to a Delphi stringlist?
: This is some of the code I have started with but no exception is being raised so I am sure I am missing something. Thanks.

: for iTemp := 0 to frmData.sgClasses.Rowcount - 1 do
: begin
: try
: slGeneratedTemp.Add(frmData.sgClasses.Cells[11,iTemp]);
: except
: on EStringListError do showmessage('duplicate scan codes');
: end;
: end;

------------------------------------

For an exception to be raised when you add a duplicate, you should set two properties of the Delphi stringlist:
- set Sorted to True;
- set Duplicates to dupError.

In the following example, all the animals are added to the stringlist, except for the second 'cat':

procedure TForm1.Button1Click(Sender: TObject);
const
  Animals: array[1..4] of string = ('cat', 'dog', 'cat', 'bird');
var
  SL: TStringList;
  i: integer;
begin
  SL := TStringList.Create;
  SL.Sorted := True;
  SL.Duplicates := dupError;
  for i := 1 to 4 do
    try
      SL.Add(Animals[i]);
    except
      on EStringListError do
        Showmessage('Duplicate at ' + IntToStr(i) + ': ' + Animals[i]);
    end;
  SL.Free;
end;


Related Articles and Replies:


[ Related Articles and Replies ] [ DelphiLand Discussion Forum ]