gpt4 book ai didi

delphi - 检查列表框中是否已选择某个项目

转载 作者:行者123 更新时间:2023-12-03 14:59:38 24 4
gpt4 key购买 nike

当用户单击标签时,我想检查列表框中是否已选择某个项目
如果我像这样执行,我会收到此错误列表索引超出范围

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;

最佳答案

这段代码

if Selected then

不会编译,因为Selected是一个字符串。我猜您在发布此内容之前正在尝试。

尽管如此,您的错误消息和问题标题表明 ListBox1.ItemIndex 等于 -1。因此会出现列表索引越界错误。

在从列表框中读取数据之前,您需要添加一个检查以确保 ListBox1.ItemIndex 不为 -1。 ItemIndex=-1 是检测没有选择任何项目的方法。因此,您的代码应如下所示:

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

关于delphi - 检查列表框中是否已选择某个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10252230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com