[1, 3]
消息框总是说我输入的是“输入错误”,只有出现第一个“ if”的消息框,当我键入正确的名称(某物)时,它也出现在代码的第一部分:(
private void Submit_Click(object sender, EventArgs e)
{
if (textBox_Name.Text.Length == 0 && (textBox_Name.Text != "something" || textBox_Name.Text != "something"))
{
string message = "Your name is not " + textBox_Name.Text;
string caption = "Error input";
MessageBoxButtons buttons = MessageBoxButtons.RetryCancel;
MessageBox.Show(message, caption, buttons);
textBox_Name.Clear();
else
MessageBox.Show("Good job something you know your name, LOL");
}
语句甚至没有被检查。
我正在验证Windows窗体应用程序中文本框的内容。
答案 0 :(得分:-1)
在我看来,就像您弄糟了if / else条件(如果我理解您要正确执行的操作)。
这是应该起作用的代码:
private void Submit_Click(object sender, EventArgs e)
{
if (textBox_Name.Text == "OptionA" || textBox_Name.Text == "OptionB")
MessageBox.Show("Good job, at least you know your own name, LOL");
else
{
string message = "Your name is not " + textBox_Name.Text;
string caption = "Error input";
MessageBoxButtons buttons = MessageBoxButtons.RetryCancel;
MessageBox.Show(message, caption, buttons);
textBox_Name.Clear();
}
}
答案 1 :(得分:-1)
您的测试逻辑在括号内显得很奇怪。
if ((textBox_Name.Text.Length == 0) && ((textBox_Name.Text != "something") || (textBox_Name.Text != "something")))
以缩写形式仅显示上下文
if(( textLength == 0 && ( text != "something" || text != "something" ) ))
请注意,您的文本长度本身就是全部,然后是(x OR x)的AND。只有在文本框中有一个空字符串时,它才会返回TRUE。因为字符串长度将为零长度,而实际文本不会是“某物”。
您可能需要进行更多测试,例如...
if( string.IsNullOrWhiteSpace( textBox_Name.Text ))
{
MessageBox.Show("You have not entered a value for the name");
return;
}
if( textBox_Name.Text.Equals( "something", StringComparison.CurrentCultureIgnoreCase )
{
string message = "Your name is not " + textBox_Name.Text;
string caption = "Error input";
MessageBoxButtons buttons = MessageBoxButtons.RetryCancel;
MessageBox.Show(message, caption, buttons);
textBox_Name.Clear();
return;
}
// else, must have had something valid other than empty or "something" regardless of case.
MessageBox.Show("Good job something you know your name, LOL");