Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this IF statement return false?

Tags:

c#

.net

I have two text boxes and I want skip a block of code only when both are empty:

if (txtBox1.Text.Trim() != string.Empty && txtBox2.Text.Trim() != string.Empty )
{
     // Do something
}

If either of the text boxes has something, I want the //Do something part to execute. Only when both are empty do I want to skip.

However the above code fragment doesn't work. Why?

like image 605
John Klasius Avatar asked Nov 20 '09 16:11

John Klasius


People also ask

Why does an if statement return false?

Re: if statement returning only false condition value Then, it evaluates if TRUE (or FALSE) is less than C16. That's where your formula breaks as it will always return FALSE. Now, you could turn a TRUE or a FALSE into a 1 or a 0, but then the outcome would most likely always be TRUE.

Why is my Excel formula showing false?

FALSE Function in Excel. The FALSE function in Excel is a logical function that returns “FALSE” as an output when used in a blank cell. This function also does not take any arguments similar to the TRUE function in Excel.

How do I get Excel to stop saying false?

You can prevent these indicators from being displayed by using the following procedure. In Excel 2016, Excel 2013, and Excel 2010: Click File > Options >Formulas. > Excel Options > Formulas. Under Error Checking, clear the Enable background error checking check box.

Why does Excel say false when true?

The reason for this is that the 'words' TRUE and FALSE are actually the numbers 1 and 0 in Excel (in most cases). So when you are creating the logical test in the IF function, you must treat it like a number i.e. no inverted commas.


2 Answers

I believe you have your logical operators mixed up. What you're looking for is

if (txtBox1.Text.Trim() != string.Empty || txtBox2.Text.Trim() != string.Empty )
{
     // Do something
}
like image 148
CrimsonX Avatar answered Oct 05 '22 10:10

CrimsonX


You should replace your && with ||. Currently, the code in the if block will only be executed if both text fields have text in them.

like image 28
Thomas Owens Avatar answered Oct 05 '22 12:10

Thomas Owens