Add items in a listpicker .. errors
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
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:
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.
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.
精彩评论