2013-07-14 41 views
0

我正嘗試使用索引將項目從array of strings添加到listView。 以下是我的代碼:根據空間拆分包含字符和數字的字符串

using (StringReader tr = new StringReader(Mystring)) 
{ 
    string Line; 
    while ((Line = tr.ReadLine()) != null) 
    { 
     string[] temp = Line.Split(' '); 
     listview1.Items.Add(new ListViewItem(temp[1], temp[3])); 
    } 
} 

但它提供了一個index out of bound error

當我不使用索引

listview1.Items.Add(new ListViewItem(temp)); 

它工作正常,並增加了數組的內容到ListView。

而且它還將零索引字符串添加到listView。對於一個,兩個或其他索引,它會給出相同的錯誤。

請任何人告訴我如何使用索引或任何其他方法只將我需要的字符串添加到listView。 在此先感謝!

+1

'temp [1],temp [3]'是數組的第二和第四個元素。你實際上有4個元素在數組中? – Oded

+0

是的,我同意Oded,你可能意思是temp [0],temp [2] – prospector

+2

你試圖添加的行看起來像什麼?您是否通過異常進行調試,以查看拋出異常時'temp'的值是什麼? – Oded

回答

1

如果字符串以換行符結尾,您將得到一個空字符串作爲最後一行。跳過任何空行:

using (StringReader tr = new StringReader(Mystring)) { 
    string Line; 
    while ((Line = tr.ReadLine()) != null) { 
    if (Line.Length > 0) { 
     string[] temp = Line.Split(' '); 
     listview1.Items.Add(new ListViewItem(temp[1], temp[3])); 
    } 
    } 
} 

Additionaly,你可以檢查分裂後的數組的長度,但我相信,如果有什麼事情該行的話,那將是正確的。

+0

這看起來像一個很好的答案,可以幫助OP,但是沒有任何OP的迴應。 :) –

+0

感謝Guffa它爲我工作。空串是問題 –

相關問題