Question

string cstring = e.Result;
            string[] delim = {"<br>","*"};
            string[] cstringl = cstring.Split(delim, StringSplitOptions.None);
            for (int i = 0; i < cstringl.Length; i++)
            {
                country_picker.Items.Add(cstringl[i]);
            }

I am using the above mentioned code to add items in a listbox named country picker, but i get indexoutofrange exception. Why am i getting this error when i have checked the length using i<=cstring1.Length

Was it helpful?

Solution

I see 2 issues with your code.

Update it as below:

for (int i = 0; i < cstringl.Length; i++) 
{ 
    country_picker.Items.Add(cstringl[i]); 
} 

The 2 changes are:

  1. the comparision in the for loop to be "less than" the length, not "less than or equal to" as this will trigger an off by oe error due to Length being the count but the array being zero indexed. This is th cause of your IndexOutOfRangeException.

  2. Using the loop variable as an index reference when adding the item. So you don't get the same (first) item added multiple times.

Update
Having looked at your code again, another possible issue could be caused by theinitial value of e.result. Try using StringSplitOptions.RemoveEmptyEntries so you don't risk trygin to enter empty values. Also add a check that cstringl contains at least one item.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top