[英]Creating listbox items from a large string
I have a large string that contains text: 我有一个包含文本的大字符串:
"value 1
value 2
value 3
etc..." //over 100 values
I am trying to create a listbox with it's items based on the values in this string. 我正在尝试基于此字符串中的值创建一个带有其项目的列表框。
I used a try catch as I was getting an argument out of range exception which stopped the error but I can't see any items in the listbox :P 我使用了try catch,因为我得到了超出范围异常的参数,该异常停止了错误,但我在列表框中看不到任何项目:P
string value = "";
int currentIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(listStr, "\r\n?"))
{
try
{
value = formatted.Substring(currentIndexPos, m.Index - 1); // -1 so the matched value isn't used.
listBox1.Items.Add(value);
currentIndexPos = m.Index + 1;
}
catch
{
//argument out of range exception
//Index and length must refer to a location within the string. Parameter name: length
}
}
Try something like this 试试这个
var values = listStr.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(string value in values)
{
listBox1.Items.Add(value);
}
As many have said, just use String.Split. 正如许多人所说,只需使用String.Split。 However, there's no need for a foreach loop or resorting to LINQ, just do this: 但是,不需要foreach循环或诉诸LINQ,只需执行以下操作:
listBox1.Items.AddRange(String.Split(...));
Since you are in essence doing a split why not use that function and ignore the index operations. 由于本质上是在进行拆分,所以为什么不使用该函数并忽略索引操作。
var lst = String.Split("\r".ToCharArray(),"listStr");
lst.select((x)=>listBox1.Items.Add(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.