简体   繁体   中英

Validating xamarin.forms picker

I use this code to get the selected item on my picker:

var loanType = picker.Items[picker.SelectedIndex];

I want to validate the picker when nothing is selected but it returns:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

I understand that it's because nothing is selected, so I wanted to ask if there is any workaround to this. I use syntax picker.Items[picker.SelectedIndex]; instead of pickerPaymentMode.SelectedIndex because the picker's item source is from a list coming from a JSON response via API

If nothing is selected in the picker, the value of picker.SelectedIndex is -1 .

So you can check everytime you use picker.SelectedIndex :

    if (picker.SelectedIndex != null && picker.SelectedIndex >=0)
    {
        var loanType = picker.Items[picker.SelectedIndex];

    }
    else
    {
        Console.WriteLine(picker.SelectedIndex);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM