Search code examples
c#xamarinbindingpickerselecteditem

Picker error "Specified cast is not valid" when getting the SelectedItem value in Xamarin Forms


I have a picker, already set with the bindings, but when I'm trying to copy the selecteditem value to a variable but shows error "System.InvalidCastException: 'Specified cast is not valid'. The info contained in the selected item is actually correct, this is my code:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem);

also tried this (didn't work either, different error thrown tho):

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem as Pisteros);

Pisteros being the model in used.

Error:

Error

Also I have the binding for the same object on SelectedIndex, but this one still returns the index and not the PisteroID which is what I need, but if I use the following:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedIndex);

the value does gets copied to the variable without issues


Solution

  • It's hard to tell what you actually want or the types involved. However, it could be you are looking for.

    IDPisteroMainPage = Convert.ToInt32(((Pisteros)pck_Pisteros.SelectedItem).PisteroId);
    
    // or slightly more fault tolerant if you expect a null 
    if(pck_Pisteros.SelectedItem is Pisteros pisteros)
       IDPisteroMainPage = pisteros.PisteroId;
    else
       // handle null (if need be)
       
    
    // or if PisteroId is an int and SelectedItem is never null
    IDPisteroMainPage = ((Pisteros)pck_Pisteros.SelectedItem).PisteroId