I am having an issue with my ListPicker control. I have implemented my listpicker in my page as follows but I am receiving an IndexOutOfRangeException upon runtime, and I am not quite sure of how to fix the problem:
SettingsPage.xaml
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="SearchProviderItemTemplate">
<TextBlock Text="{Binding SearchProvider}" />
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<ScrollViewer x:Name="ContentPanel_Browser" Margin="12,0,12,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
...
<!-- Search Provider -->
<TextBlock Text="Search provider" Margin="12,7,12,8"
Grid.Row="3" VerticalAlignment="Bottom"
Foreground="{StaticResource PhoneSubtleBrush}"/>
<toolkit:ListPicker x:Name="SearchProviderListPicker" Grid.Row="4" Grid.ColumnSpan="2" Margin="12,0,12,0"
ItemTemplate="{Binding SearchProviderItemTemplate}"
SelectionChanged="SearchProviderListPicker_SelectionChanged" />
</Grid>
</ScrollViewer>
SettingsPage.xaml.cs
string searchProvider;
String[] SearchProvider =
{
"Google",
"Bing",
"Yahoo",
"Ask",
"AOL"
};
private void SearchProviderListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem = e.AddedItems[0] as string; //IndexOutOfRangeException was unhandled
switch (selectedItem)
{
case "Google":
searchProvider = "http://www.google.com/search?q=";
break;
case "Bing":
searchProvider = "http://www.bing.com/search?q=";
break;
case "Yahoo":
searchProvider = "http://search.yahoo.com/search?p=";
break;
case "Ask":
searchProvider = "http://www.ask.com/web?q=";
break;
case "AOL":
searchProvider = "http://search.aol.com/search?q=";
break;
//default:
// SearchProvider = "http://search.aol.com/search?q=";
// break;
}
The IndexOutOfRangeException occurs with line ‘string selectedItem = e.AddedItems[0] as string;’ in SettingsPage.xaml.cs. I remember seeing how to solve this somewhere on StackOverflow but I cannot find that source now. Any idea on how to set the bounds or check to ensure this exception will not occur? Thanks in advance (any code assistance would help I am new to this!).
As
AddedItemsis an IList, can you not just make a check that it has some items in it before you try and access them?Something like the following at the top of the method should solve the problem: