首页 > 解决方案 > 仅接受用户输入中的某些字符

问题描述

我有这段代码,但应用程序进入中断模式并告诉我有一个未处理的异常:当用户输入除 A、B、C、DI 以外的任何内容时,值不能为空 已经解决了这个问题,但我的代码似乎不起作用.

 private async void Confirm_Clicked(object sender, EventArgs e)
    {
        if (txtUserEntry.Text != null)
        {
            if (txtUserEntry.Text == "A")
            { 
                await DisplayAlert("Wrong answer", "Sorry", "Next question");
                await Navigation.PushModalAsync(new Quiz_Page2());
            }
            else if (txtUserEntry.Text == "B")
            {
                await DisplayAlert("Wrong answer", "Sorry", "Next question");
                await Navigation.PushModalAsync(new Quiz_Page2());
            }
            else if (txtUserEntry.Text == "C")
            {
                await DisplayAlert("Wrong answer", "Sorry", "Next question");
                await Navigation.PushModalAsync(new Quiz_Page2());
            }
            else if (txtUserEntry.Text == "D")
            {
                scoreSettings.GlobalScore++;
                await DisplayAlert("Correct answer", "Well done", "Next question");
                await Navigation.PushModalAsync(new Quiz_Page2());
            }
            else if (txtUserEntry.Text != "A" || txtUserEntry.Text != "B" || txtUserEntry.Text != "C" || txtUserEntry.Text != "D")
            {
                await DisplayAlert("Please type either A,B,C,D", "", "");
            }

            else await DisplayAlert("Please type either A,B,C,D", "", "");
        }
    }
}

标签: c#xamarin

解决方案


原因: 该方法DisplayAlert有三个参数

//   title:
//     The title of the alert dialog.
//
//   message:
//     The body text of the alert dialog.
//
//   cancel:
//     Text to be displayed on the 'Cancel' button.

它们是Nonnullable。因此,当您将其设置为 null 时,它会崩溃。

解决方案:

给出参数messagecancel值。如果你不想让它显示任何东西。你可以将它们设置为space

 await DisplayAlert("Please type either A,B,C,D", " ", " ");

推荐阅读