我想检查当用户点击标签时
是否在ListBox中选择了一个项目,如果我执行就像我得到了这个错误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;
Run Code Online (Sandbox Code Playgroud)
这段代码
if Selected then
Run Code Online (Sandbox Code Playgroud)
不会编译因为Selected是一个字符串.我猜你在发布之前就在试验.
所有相同的错误消息和问题标题表明它 ListBox1.ItemIndex 等于-1.因此列表索引超出界限错误.
ListBox1.ItemIndex在从列表框中读取之前,您需要添加一个非-1 的检查.ItemIndex=-1是您检测到没有选择任何项目的方式.因此,您的代码应如下所示:
.....
saveDialog.DefaultExt := 'txt';
saveDialog.FilterIndex := 1;
if ListBox1.ItemIndex <> -1 then
begin
.....
Run Code Online (Sandbox Code Playgroud)