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 😛
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
}
}
As many have said, just use String.Split. However, there’s no need for a foreach loop or resorting to LINQ, just do this: