delphi – 检查ListBox中是否已选择某个项目
发布时间:2020-12-15 09:31:27 所属栏目:大数据 来源:网络整理
导读:我想检查用户点击标签时是否在ListBox中选择了一个项目 如果我这样执行,我得到这个错误列表索引超出范围 procedure TfrMain.Label15Click(Sender: TObject);var saveDialog : TSaveDialog; FileContents: TStringStream; saveLine,Selected : String;begin s
我想检查用户点击标签时是否在ListBox中选择了一个项目
如果我这样执行,我得到这个错误列表索引超出范围 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 ..... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |