2012-04-20 49 views
4

被选中我想如果一个项目已在ListBox中被选中时标签
用户点击,如果我执行这样我得到这个错误list index out of bounds
检查项目已在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; 

回答

4

此代码

if Selected then 

不能编译,因为Selected是一个字符串。我想你在发布之前正在做实验。

所有相同的错误消息和问题标题暗示ListBox1.ItemIndex等于-1。因此列表索引越界错误。

您需要在从列表框中读取之前添加一个检查ListBox1.ItemIndex不是-1。 ItemIndex=-1是您检测未选择任何项目的方式。因此,您的代码应该是这样的:

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

它是我尝试了很多事情来测试'Selected'就像'如果选择<>'''并且因为我不知道如何测试它而结束了,反正谢谢 – 2012-04-20 19:31:24

2

此检查如果没有在列表框中选择任何内容,则会发生。

尝试使用:

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; 
+0

如果你提到我的代码是在说'如果ListBox1.ItemIndex> = 0'(大于或等于0),如你所知'ItemIndex'是类型'整数'并且-1和0之间没有其他整数值,所以'ItemIndex> = 0'肯定等于'ItemIndex> -1';) – 2012-04-20 23:00:19

+0

但是它很难阅读,而且不是它通常写的方式。发布难以阅读的代码从来都不是很好,特别是当你将它发布给显然是相当新的语言的人时。尽管如此,你是对的。从技术上讲这没有错,我会删除我的评论。 (尽管如此,仍然必须给大卫以赞赏:))你写的东西等同于写'if(something = true)和(something <> false)然后' - 这是多余的,不必要的测试。 '如果ItemIndex> -1'是相同的测试,并且含义更清晰。 – 2012-04-20 23:02:50

+0

正如你在第一条评论中提到的那样,ItemIndex是基于零的,所以如果你把它比作零而不是-1,它就不会“难以阅读”。 ;) – 2012-04-20 23:10:29