2012-04-20 28 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