Xamarin Forms Picker中的System.ArgumentOutOfRangeException

时间:2018-10-18 09:28:59

标签: c# xamarin xamarin.forms

我在Xamarin Forms中使用一个选择器,如果用户选择它,我将从选择器中获取选择的值。

  if (loantype.Items[loantype.SelectedIndex] != null)
{
    //If user selects a value , code goes here
}

但是,如果用户未从选择器中选择一个值,则应进行检查。我想检查对象内部是否为空。

  AddNewTeam addnewteam = new AddNewTeam
         {

             first_name = firstname.Text,
             last_name = lastname.Text,
             email = email.Text,
             mobile = mobile.Text,


         };

但是我得到

  

System.ArgumentOutOfRangeException

已引发错误。我也尝试了不同的解决方案。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

ArgumentOutOfRangeException是由于索引项大于列表/数组的大小或负数的结果。 Picker没有选择值时的事件,但确实有SelectedIndexChanged事件。例如:

<Picker
    ItemsSource="{Binding LoanTypesSelection}"
    SelectedIndexChanged="Handle_SelectedIndexChanged"/>

我已为此Picker分配了一个事件,以便当索引确实发生更改时,它将触发Handle_SelectedIndexChanged,否则不会发生/更改

在处理程序中,我有:

public string[] LoanTypesSelection => new string[]
{
    "Student Loan",
    "Mortgage"
};

void Handle_SelectedIndexChanged(object sender, System.EventArgs e)
{
    if(!(sender is Picker loantype))
    {
        return;
    }

    if ((loantype.SelectedIndex > LoanTypesSelection.Length) ||
        (loantype.SelectedIndex < 0))
    {
        // Display an error message?
        return;
    }

    MyLabel.Text = LoanTypesSelection[loantype.SelectedIndex]; // Or whatever
}

答案 1 :(得分:0)

检查Count(或Length)属性是否等于0。现在您正在索引空数组。

答案 2 :(得分:0)

在选择器上未选择任何值时,其SelectedIndex将为-1。在IList上访问-1会引发异常。相反,只需检查datePicker.minimumDate = Date()是否有效

SelectedIndex