表单保留textBox值 - 重置?

时间:2012-06-07 14:06:16

标签: c# textbox

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

    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();           
    }

6 个答案:

答案 0 :(得分:3)

这条线有两个原因错误

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

    所以正确的行是

    if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
    {
        MessageBox(......);
    
        // See the comment below
        textBox1.ResetText();    
        textBox2.ResetText();   
    } 
    

    如果您想要在出现错误时重置文本框,或者您想要像现在一样重置,请不要清楚您的问题。如果只想在发生错误时重置,请移动if块

    中的两个ResetText

答案 1 :(得分:0)

WinForms Texbox在我的体验中从未显示null,而是返回String.Empty

您可以使用String.IsNullOrEmpty(textBox1.Text)检查这两种情况。如果你使用的是.Net 4,你可以使用String.IsNullOrWhiteSpace(textBox1.Text),它也会为空格返回true。

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

答案 2 :(得分:0)

使用

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

而不是

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

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

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

答案 3 :(得分:0)

if ((textBox1.Text == String.Empty) || (textBox2.Text == String.Empty))

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

答案 4 :(得分:0)

TextBox的.Text属性永远不会为null。你要找的是一个空字符串,所以:

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))

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

答案 5 :(得分:0)

虽然我没有说服文本框可以使用空值,但我使用String.IsNullOrEmpty

if(String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text))
{
    //...
}