Question: I want to check if an item has been selected in ListBox when user click on label   

if i execute like that i got this error `list index out of bounds`  

```
procedure TfrMain.Label15Click(Sender: TObject);
var
 saveDialog : TSaveDialog;
 FileContents: TStringStream;
 saveLine,Selected : String;
begin
 saveDialog := TSaveDialog.Create(self);
 saveDialog.Title := 'Save your text or word file';
 saveDialog.InitialDir := GetCurrentDir;
 saveDialog.Filter := 'text file|*.txt';
 saveDialog.DefaultExt := 'txt';
 saveDialog.FilterIndex := 1;

 Selected := ListBox1.Items.Strings[ListBox1.ItemIndex]; 

 if Selected <> '' then
 begin
  if saveDialog.Execute then
  begin
   FileContents := TStringStream.Create('', TEncoding.UTF8);
   FileContents.LoadFromFile(ListBox1.Items.Strings[ListBox1.ItemIndex]);
   FileContents.SaveToFile(saveDialog.Filename);
   ShowMessage('File : '+saveDialog.FileName)
  end
 else ShowMessage('Save file was not succesful');
  saveDialog.Free;
 end;
end;

```

Answer: 
This code

```
if Selected then

```

will not compile because `Selected` is a string. I guess you were experimenting just before posting this.

All the same you error messages and the question title suggests that `ListBox1.ItemIndex` is equal to -1. Hence the list index out of bounds error.

You need to add a check that `ListBox1.ItemIndex` is not -1 before reading from the list box. `ItemIndex=-1` is the way you detect that no item is selected. Your code should therefore look like this:

```
.....
saveDialog.DefaultExt := 'txt';  
saveDialog.FilterIndex := 1; 
if ListBox1.ItemIndex <> -1 then
begin
.....

```
This occurs if nothing is selected in the list box.

Try Using:

```
procedure TfrMain.Label15Click(Sender: TObject);
var
 saveDialog : TSaveDialog;
 FileContents: TStringStream;
 saveLine,Selected : String;
begin
 saveDialog := TSaveDialog.Create(self);
 saveDialog.Title := 'Save your text or word file';
 saveDialog.InitialDir := GetCurrentDir;
 saveDialog.Filter := 'text file|*.txt';
 saveDialog.DefaultExt := 'txt';
 saveDialog.FilterIndex := 1;

 if ListBox1.ItemIndex >= 0 then
 begin
  Selected := ListBox1.Items.Strings[ListBox1.ItemIndex]
  if saveDialog.Execute then
  begin
   FileContents := TStringStream.Create('', TEncoding.UTF8);
   FileContents.LoadFromFile(Selected);
   FileContents.SaveToFile(saveDialog.Filename);
   ShowMessage('File : '+saveDialog.FileName)
  end
 else ShowMessage('Save file was not succesful');
  saveDialog.Free;
 end;
end;

```