Menno K
Menno K

Reputation: 89

Picker gives me an ArgumentOutOfRangeException, why is this happening?

I need my picker to hide elements if authorization == true.

    private async void Picker_Unfocused(object sender, FocusEventArgs e)
    {
        try
        {
            await DisplayAlert("try", picker.SelectedIndex.ToString(), "OK");

            if (response.domains[picker.SelectedIndex].authorization == true)
            {
                userNameEntry.IsVisible = false;
                passwordEntry.IsVisible = false;
                userLabel.IsVisible = false;
            }
            else
            {
                userNameEntry.IsVisible = true;
                passwordEntry.IsVisible = true;
                userLabel.IsVisible = true;
            }
        }
        catch(System.ArgumentOutOfRangeException)
        {
            await DisplayAlert("catch", picker.SelectedIndex.ToString(), "OK");
        }
    }

This won't help. I get an ArgumentOutOfRangeException. Does anyone know why? It is important to me that this works.

Edit: Code is now current code. displayalerts just give me 0 if I select the first item, 1 if I select the second, etc. I still don't know what's going on. If the value of SelectedIndex is 0(or whatever I select) I shouldn't get an ArgumentOutOfRangeException, right?

Upvotes: 0

Views: 95

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 33993

When the picker is not yet initialized or can view a null value and is thus empty, the SelectedIndex property will give you a value of -1. This value is not valid for use in an array.

You should enrich your code to account for this possibility, for instance like this:

if (picker.SelectedIndex > -1 && response.domains[picker.SelectedIndex].authorization == true)
{
    userNameEntry.IsVisible = false;
    passwordEntry.IsVisible = false;
    userLabel.IsVisible = false;
}
else
{
    userNameEntry.IsVisible = true;
    passwordEntry.IsVisible = true;
    userLabel.IsVisible = true;
}

Upvotes: 1

Related Questions