0

I basically have a listview, with this function when i click on a listview-item.

When i run this and click on the item, i get the following display alerts before my app crashes.

DisplayAlert 1, then DisplayAlert 2, then DisplayAlert 1 and right after this one my app crashes. With "Specified cast is not valid".

I dont know why i get the DisplayAlert 1 again, and why this crashes.

public async void OnSelection(object sender, SelectedItemChangedEventArgs e)
    {
        await DisplayAlert("1", "1", "1");
        if (e.SelectedItem == null)
        {
            return; // ItemSelected is called on deselection, which results in SelectedItem being set to null
        }

        //((ListView)sender).SelectedItem = null;

        await DisplayAlert("2", "2", "2");
        // Cast to zoneviewmodel type
        var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem; 


        await DisplayAlert("3", "3", "3");
        // Redirect to login
        await Navigation.PushAsync(new LoginPage(selectedZone.Address));

        await DisplayAlert("4", "4", "4");
        // send message containing information to fill loginpage information
        MessagingCenter.Send<MainPage, ViewModel.ZoneViewModel>(this, "loginInfo", selectedZone);
    }
Jazz W
  • 139
  • 2
  • 12
  • what is the exception message you get? and it seems your OnSelection event is firing two times – Eddy Jul 06 '17 at 14:23
  • What do type of object do you put in your list? – Jordy Dieltjens Jul 06 '17 at 14:26
  • Unhandled Exception:System.InvalidCastException: Specified cast is not valid. occurred @Eddy – Jazz W Jul 06 '17 at 14:28
  • Ah ok @JazzW, then this line is causing the exception: `var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem; ` SelectedItem is not of type ZoneViewModel... Try to debug and see the exact type of SelectedItem – Eddy Jul 06 '17 at 14:31

1 Answers1

0

In this line: var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem; you're trying to cast whatever is in your list to ViewModel.ZoneViewModel. The error is telling you this list item is not assignable to this type. If you're not sure what type the item is, step through or print out e.SelectedItem.GetType().

Jon B
  • 51,025
  • 31
  • 133
  • 161
  • I have edited and added a printscreen, from the ViewModel.ZoneViewModel.cs. My list is an ObserableCollection : /// private static ObservableCollection Zones; – Jazz W Jul 06 '17 at 14:33
  • @JazzW You'll need to set a breakpoint on that line to see what exactly `SelectedItem` is. – Jon B Jul 06 '17 at 14:41