1

我有一个表格检查几个文本框不为空。如果其中任何一个是,它应该显示一个消息框,重置文本框并让用户重试。我相信我在检查文本框错误。我怎样才能做到这一点?谢谢。

    public void ShowPaths()
    {
        if (textBox1.Text == null | textBox2.Text == null)
        {
            MessageBox.Show("Please enter a Project Name and Number");
        }
        else
        {
            sm.projNumber = textBox1.Text;
            sm.projName = textBox2.Text;

            textBox3.Text = sm.Root("s");
            textBox4.Text = sm.Root("t");
        }
        textBox1.ResetText();
        textBox2.ResetText();           
    }
4

6 回答 6

3

这条线是错误的,有两个原因

if (textBox1.Text == null | textBox2.Text == null) 
  1. 当您阅读时, textbox.Text 永远不会为空,它是一个空字符串
  2. |当您应该使用逻辑运算时,您正在使用按位 OR 运算符||

所以正确的线是

if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
    MessageBox(......);

    // See the comment below
    textBox1.ResetText();    
    textBox2.ResetText();   
} 

从您的问题中不清楚您是否想在出现错误时重置文本框,或者您是否想像现在一样始终重置。如果您只想在出错的情况下重置,请在 if 块内移动两个 ResetText

于 2012-06-07T14:09:48.427 回答
0

TextBox 的 .Text 属性永远不会为空。您正在寻找的是一个空字符串,所以:

if (textBox1.Text.Equals(string.Empty) || textBox2.Text.Equals(string.Empty))

或者

if (textBox1.Text == "" || textBox2.Text == "")

或者

if (String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text))

运算符也|应该是 a 。||但这只是问题的一部分。

于 2012-06-07T14:10:01.343 回答
0

WinForms Texboxesnull在我的经验中从未显示,而是返回String.Empty.

您可以使用String.IsNullOrEmpty(textBox1.Text)来检查任何一种情况。如果您使用的是 .Net 4,您也可以使用String.IsNullOrWhiteSpace(textBox1.Text)which 也会为空格返回 true。

if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
于 2012-06-07T14:08:09.010 回答
0

利用

  if (textBox1.Text == null || textBox2.Text == null)

代替

  if (textBox1.Text == null | textBox2.Text == null)

您没有OR (||)正确使用运算符。

用于String.IsNullorEmpty(string)检查字符串变量中的 NULL 和空白值。

于 2012-06-07T14:08:28.617 回答
0
if ((textBox1.Text == String.Empty) || (textBox2.Text == String.Empty))

如果 Textbox1 为空或 textbox2 为空(注意 || 而不是 |) 而且 Text 属性永远不会为空。它始终是一个字符串,但它可以为空(String.Empty 或“”)

于 2012-06-07T14:08:47.840 回答
0

虽然我不相信文本框可以有我使用的空值String.IsNullOrEmpty

if(String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text))
{
    //...
}
于 2012-06-07T14:12:08.087 回答