deepseapanda
deepseapanda

Reputation: 3907

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

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
    }
}

Upvotes: 0

Views: 714

Answers (3)

rerun
rerun

Reputation: 25505

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));

Upvotes: 1

zmbq
zmbq

Reputation: 39023

As many have said, just use String.Split. However, there's no need for a foreach loop or resorting to LINQ, just do this:

listBox1.Items.AddRange(String.Split(...));

Upvotes: 2

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25465

Try something like this

var values = listStr.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(string value in values)
{
    listBox1.Items.Add(value);
}

Upvotes: 2

Related Questions