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;
This code
will not compile because
Selectedis a string. I guess you were experimenting just before posting this.All the same you error messages and the question title suggests that
ListBox1.ItemIndexis equal to -1. Hence the list index out of bounds error.You need to add a check that
ListBox1.ItemIndexis not -1 before reading from the list box.ItemIndex=-1is the way you detect that no item is selected. Your code should therefore look like this: