简体   繁体   中英

how to compare two text box and if both is empty how to print a message box in c#

i am comparing here two text box and trying to print a error message if both are empty

         int ina=int.Parse(txttea.Text);
         int inb = int.Parse(txtcoffee.Text);
         int inc=0, ind=0;
         if(this.txttea.Text=="" && this.txtcoffee.Text=="")
          {
            MessageBox.Show("select a item");
            txttea.Focus();
          }

Instead of && you need || in the line:

if(this.txttea.Text=="" && this.txtcoffee.Text=="")

Note: The question does not correspond with the title of it.

Your question is how to validate the TextBox if is empty or white space .

The best way to deal withi this by using the String.IsNullOrWhiteSpace Method if you're in .Net 3.5 or later

 if(string.IsNullOrWhiteSpace(txttea.Text) || 
    string.IsNullOrWhiteSpace(txtcoffee.Text))
          {
            MessageBox.Show("select a item");
            txttea.Focus();
            return;
          }

Should be the following below please edit your question to match the provided answer below

 int ina=int.Parse(txttea.Text);
 int inb = int.Parse(txtcoffee.Text);
 int inc=0, ind=0;
 if(this.txttea.Text=="" || this.txtcoffee.Text=="")
 {
     MessageBox.Show("select an item");
     txttea.Focus();
 }

Parsing the empty string with int.Parse will give you an exception. I mean: int.Parse("") results in: Input string was not in a correct format.

To solve that problem, use TryParse instead:

int ina;
int inb;
if (int.TryParse(txttea.Text, out ina) && int.TryParse(txtcoffee.Text, out inb))
{
    //Ok, more code here
}
else
{
    //got a wrong format, MessageBox.Show or whatever goes here
}

You can also test them separately, of course [first ina then inb, or vice versa]:

int ina;
if (int.TryParse(txttea.Text, out ina))
{
    int inb;
    if (int.TryParse(txtcoffee.Text, out inb))
    {
        //Ok, more code here
    }
    else
    {
        //got a wrong format, MessageBox.Show or whatever goes here
    }
}
else
{
    //got a wrong format, MessageBox.Show or whatever goes here
}

Now, about comparing for the empty string, if you want the message when BOTH are empty:

if(this.txttea.Text == "" && this.txtcoffee.Text == "")
{
    MessageBox.Show("select a item");
    txttea.Focus();
}

On the other hand if you want the message when AT LEAST ONE is empty:

if(this.txttea.Text == "" || this.txtcoffee.Text == "")
{
    MessageBox.Show("select a item");
    txttea.Focus();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM