【问题标题】:How to check for empty textbox如何检查空文本框
【发布时间】:2014-07-03 06:38:27
【问题描述】:

在一个网站上我找到了TryParse 方法(如何检查C#中是否有空文本框),但我不知道如何使用它。

int outputValue=0;
bool isNumber=false;
isNumber=int.TryParse(textBox1.Text, out outputValue); 
if(!isNumber)
{
 MessageBox.Show("Type numbers in the textboxes");
}
else
{
// some code
}

我该如何解决超过 1 个文本框的问题

【问题讨论】:

  • 哪一点让您感到困惑? (顺便说一句,您提供的代码没有检查文本框是否为空)
  • String.IsNullOrEmpty 用于检查文本是否为空或为空。
  • 这不会检查空复选框。它会让你知道文本框中的文本是否为整数。
  • 解决什么?如果 TryParse 无法将值解析为 Int(例如,如果 Text 为空),它将返回 false - 所以 else 分支中的任何内容都会被执行...

标签: c# tryparse


【解决方案1】:

如果你想检查页面中所有文本框控件是否为空。试试IsNullOrWhiteSpace

 foreach (Control child in this.Controls)
    {
        TextBox textBox = child as TextBox;
        if (textBox != null)
        {
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                MessageBox.Show("Text box can't be empty");
            }
        }
    }

【讨论】:

  • “this.Controls”到底是什么?对我来说,它会抛出一个错误,说“(页面名称)不包含控件的定义”
【解决方案2】:

您不需要使用 TryParse 函数。上面示例中的 TryParse 函数将尝试将 textBox1 的文本转换为值 outputValue。

如果成功,则布尔值 isNumber 为真,参数 outputValue 获取的是 Textbox 转换为 int 的值。

如果失败,'IsNumber' 属性将保持为 false,并且属性 outputValue 永远不会改变。

基本上,如果您需要检查文本框是否为空,您可以使用:

if (string.IsNullOrEmpty(textbox1.Text) || string.IsNullOrEmpty(textbox2.Text) || string.IsNullOrEmpty(textbox3.Text) || string.IsNullOrEmpty(textbox4.Text)) 
{
    // At least 1 textbox is empty.
} 
else
{
    // All the textboxes are filled in.
}

【讨论】:

  • 我怎样才能为所有文本框解决这个问题,所以例如我需要 4 个 texboxes。我需要分别为所有 texoxes 编写代码吗?并且仅适用于字符串?我只需要 int/float/double 变量。
  • 但是如果四个都需要填写,可以使用多子句的if语句。我已经编辑了我的答案。
  • 复杂性是对的。只想补充一点,还有 string.IsNullOrWhitespace()。通常空白被认为是空的:)
【解决方案3】:

完成这项任务的多种方法

1. string.IsNullOrEmpty(textbox1.Text)  
2. textbox1.Text =    string.empty();  
3. textbox1.Text = "";

【讨论】:

    【解决方案4】:

    你可以试试这个:

    if(textBox1.Text.length==0) {
      //do something
     }
    

    【讨论】:

      【解决方案5】:

      你可以使用下面提到的代码

      if(!string.IsNullOrEmpty(textbox1.Text))
      {
         int outputValue=0;
         bool isNumber=false;
         isNumber=int.TryParse(textBox1.Text, out outputValue); 
         if(!isNumber)
           {
             MessageBox.Show("Type numbers in the textboxes");
           }
          else
          {
            // some code
          }
      }
      

      【讨论】:

      • 那个错字改了:)
      猜你喜欢
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多