2014-07-03 31 views
2

在一个网站上,我发现了尝试解析方法(如何检查在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+文本框

+1

哪位有点困惑吗? (顺便说一句,你提供的代码不检查文本框是否为空) – Sayse

+0

'String.IsNullOrEmpty'用于检查文本是否为空或空。 – Hassan

+1

这不检查空的复选框。它会让你知道文本框中的文本是否是整数。 – Enigmativity

回答

5

如果你想检查你的页面中的所有文本框控件为空。试试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"); 
      } 
     } 
    } 
4

数你并不需要使用的TryParse功能。上例中的TryParse函数将尝试将textBox1的文本转换为值outputValue。

如果成功,布尔isNumber将变为true,并且参数outputValue get将文本框的值转换为int。

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

Basiclly,如果需要检查,如果一个文本框为空,你可以使用:

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. 
} 
+0

如何解决所有文本框的问题在去,所以例如我需要4个texboxes。我是否需要分别为所有texoxes编写代码? 而仅适用于字符串?我只需要int/float/double变量。 – Sannyi97

+0

但是,如果他们需要填写所有四个,你可以使用一个带有多个子句的if语句。我编辑了我的答案。 – Complexity

+0

复杂性是对的。只是想补充一点,还有string.IsNullOrWhitespace()。通常空白被认为是空的:) –

0

您可以使用下面的menioned代码

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 
    } 
} 
+0

这是错字改变它:) –

1

许多方法来完成这个任务

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