2013-07-14 38 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它为我工作。空串是问题 –

相关问题