How to check for empty textbox

*爱你&永不变心* 提交于 2019-12-11 04:06:10

问题


On a site i found the try parse method (how to check if there is a empty textbox in C#) but i don't know how to use it.

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
}

and how can i solve this for 1+ number of textboxes


回答1:


If you want to check empty for all text box control in your page .Try 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");
            }
        }
    }



回答2:


You don't need to use the TryParse function. The TryParse function in your example above will try to convert the text of textBox1 into the value outputValue.

If it succeeds, the boolean isNumber becomes true and the parameter outputValue get's the value of the Textbox converted to an int.

If it fails, the 'IsNumber' property will stay false, and the property outputValue is never changed.

Basiclly, if you need to check if a textbox is empty you can use:

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



回答3:


Many ways to complete this task

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



回答4:


you can use the below menioned code

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


来源:https://stackoverflow.com/questions/24546604/how-to-check-for-empty-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!