Checking multiple conditions in a single If statement - C# - c#

I have a form in which there are many textBoxes from which three textboxes are required to fill in order to submit the form. I dont want to use each If block for each text box. Is there any way to use a single if statement for all the three text boxes? I am using the following code:
if (textBox1.Text != "" || textBox2.Text != "" || textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
but this code works even a single text fox is filled and the rest of the required text boxes are empty.

if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You want all conditions to pass. This fits the semantics of the logical AND operator &&.
If you have tons of textboxes, I would tend to keep them in a list:
var boxes = new List<TextBox>{
textBox1,
textBox2,
textBox3,
//...
};
if (boxes.Any(tb => string.IsNullOrEmpty(tb.Text)))
{
MessageBox.Show("Fill required fields");
}
else
{
// Code
}
I also tend to prefer to keep the exception in the if part, returning or throwing an error and ommit an else part, since that is just normal code flow. This keeps the code you expect to run as far to the left as possible.

You should change || to &&

You created a collection of or statements, so only one needs to be true in order to continue. Instead you need to and them:
if (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "")

You may define a method to test empty strings.
public class Test
{
public static bool IsEmpty(params string []args)
{
if (args.Length == 0) return true ;
return args.Any(p => string.IsNullOrEmpty(p));
}
}
To test strings,
if(!Test.IsEmpty(TextBox1.Text,TextBox2.Text,TextBox3.Text))
{
//valid
}

You use OR (||) and should use AND (&&) instead. You want ALL three textboxes to be non-empty strings. Check out the following code:
if (textBox1.Text != String.Empty && textBox2.Text != String.Empty && textBox4.Text != String.Empty)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}
You can also make a collection of TextBoxes and loop through them to check for non-empty Strings. Something like this:
List<TextBox> _lstTextBoxes = new List<TextBox>();
_lstTextBoxes.Add(textBox1);
_lstTextBoxes.Add(textBox2);
_lstTextBoxes.Add(textBox3);
Boolean checkFailed = false;
foreach(TextBox tb in _lstTextBoxes)
if(tb.Text == String.Empty)
checkFailed = true;
if(checkFailed)
MessageBox.Show("Fill required fields");
else
//code
This way you have a more generic approach to which you can easily add or remove certain textboxes.

Instead of using OR (||) use AND (&) in your condition.
Suggestion
Use Trim function from string to remove any white spaces from textbox (if required)
Instead of comparing like textBox1.Text != "" do String.IsNullOrEmpty(textBox1.Text) == false

Assuming you have 4 textboxes in total, below code will work
if ((textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "") || (textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "") ||
(textBox1.Text != "" && textBox3.Text != "" && textBox4.Text != "") || (textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "")
)
{
// Code
}
else
{
MessageBox.Show("Fill required fields");
}

Related

C# how to check the string in a textbox is what you want it to be

making a rock paper scissors game in C# for college.
I want to show message box when the player enters an invalid command (not rock, paper or scissors) . I tryed this but cant get it to work..
//if player enters wrong command they will
//this feedback
if (textBoxAttack.Text != "rock" || textBoxAttack.Text != "rock" || textBoxAttack.Text != "paper" || textBoxAttack.Text != "Paper" || textBoxAttack.Text != "scissors" || textBoxAttack.Text != "Scissors")
{
MessageBox.Show("Not a valid attack"
+ "\nPlease Enter one of the Following:"
+ "\nrock"
+ "\npaper"
+ "\nscissors");
textBoxAttack.Text = "";
}
It works if i just type in one command (eg: if (textBoxAttack.Text != "rock") )
any pointers?
Thanks.
You need && instead of ||.
However, i would prefer this concise and readable approach:
string[] allowed = { "rock", "paper", "scissors" };
if (!allowed.Contains(textBoxAttack.Text, StringComparer.CurrentCultureIgnoreCase))
{
string msg = string.Format("Not a valid attack{0}Please Enter one of the Following:{0}{1}"
, Environment.NewLine, string.Join(Environment.NewLine, allowed));
MessageBox.Show(msg);
textBoxAttack.Text = "";
}
Your boolean logic is wrong, because it will always not equal to one of the values, and thus will always be true. Change || to &&, and it should work.
Use an array, it makes your work easier.Also you can use ToLower method to make a case-insensitive check.
var values = new [] { "rock", "paper", "scissors" };
if(!values.Contains(textBoxAttack.Text.ToLower())
{
// invalid value
}
string text = textBoxAttack.Text.ToLowerInvariant();
if (text.Text != "rock" && text.Text != "paper" && text.Text != "scissors")
{
...
}
Use a dropdownlist/radiobuttons instead.
if (textBoxAttack.Text == "rock" || textBoxAttack.Text == "Paper" || textBoxAttack.Text == "Scissors")
{
//..Do What do you want
}
else
{
MessageBox.Show("Not a valid attack"
+ "\nPlease Enter one of the Following:"
+ "\nrock"
+ "\npaper"
+ "\nscissors");
textBoxAttack.Text = "";
}
Use Combo Box or 3 Buttons for this kind of problem.
Try to do the same but for example adding ToLower() at the end of each text attribute. This way you will only need to check 3 (rock, paper or scissors) becauuse the iput will be lower case ;)
And for the messageBox try something like this:
string[] message = { "Not a valid attack", "Please Enter one of the Following:", "rock", "paper", "scissors" };
if (textBoxAttack.Text.ToLower() != "rock" && textBoxAttack.Text.ToLower() != "paper" && textBoxAttack.Text.ToLower() != "scissors")
{
MessageBox.Show(string.Join("\n", message));
textBoxAttack.Text = "";
}

Check string is null or empty in linq

I have string with empty space("________")
string MyNote= Convert.ToString(Session["MyNote"]);
if(MyNote!=null || MyNote != "")
{
}
MyNote != "" does not work if string has more space so
How can I check my string is "" or null by using linq in C#?
String.IsNullOrWhiteSpace is the method you're looking for.
Indicates whether a specified string is null, empty, or consists only of white-space characters.
Alternatively, using your idea:
if(MyNote!=null && MyNote.Trim() != "")
{
}
or
if(MyNote!=null && MyNote.Trim().Length == 0)
{
}
if(MyNote!=null || MyNote.Length > 0) //or you may want to set different value than 0
{
}
This works for me:
string MyNote = Session["MyNote"] == null ? String.Empty : Session["MyNote"].ToString();

Can't understand why if statement is running code for True test result

I have an IF statement that is supposed to make sure the TextBox1.Text and TextBox2.Text do not match or are not blank. If they don't match or are not blank then it is supposed to assign the text in the boxes to two string variable. What I can't figure out is why when I leave the two textboxes blank the true statement still fires.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
There are two conditions in your if statement:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
The first one checks to make sure they don't match (so, good). The second checks to make sure that they are blank (so, bad). You want this:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
Also, what are you trying to do? The second condition is the only one you need if you really want them not to match OR not be blank - because the only time this will be false is if they are both blank.
You wrote "OR textbox are blank", you need "OR textbox are not blank"
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
As a side note, I'd replace "" with string.Empty for readability.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
And for even more readability, you can extract these big conditions
if (TextboxesDoNotMatch() || TextboxesAreNotEmpty())
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
private bool TextboxesDoNotMatch()
{
return tbStartBreak2.Text != tbEndBreak2.Text;
}
private bool TextboxesAreNotEmpty()
{
return tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty;
}
If you want it to return that they are NOT blank then you need to do this
(tbStartBreak2.Text != "" && tbEndBreak2.Text != "")
you have an OR between both conditions so when both are empty the second part will be true regardless the first part
(tbStartBreak2.Text == "" && tbEndBreak2.Text == "")

If (textBox1.Text == ("admin")) + (textBox2.Text == ("admin)) in C#

I want to use one command which will contain two "textboxes.Text" in one "If". I mean when I did this command :
If (textBox1.Text == ("admin")) + (textBox2.Text == ("admin)) or this If (textBox1.Text == ("admin) , textBox2.Text == admin)) it isn't right.
The main code is:
private void Label_Click(object sender, EventArgs e)
{
if (textBox2.Text == ("admin")) + (textBox1.Text == ("admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
Namely the thing I wanted to do is if one of two textboxes is wrong the label will show that the password or the username is wrong ... any ideas ?
The syntax for an if statement is:
if (condition) body
Your current code is:
if (textBox2.Text == ("admin")) + (textBox1.Text == ("admin"))
... which is treating textBox2.Text == ("admin") as the condition, and then trying to use + (textBox1.Text == ("admin")) as the body, which isn't valid. The problems are:
You're closing the condition too early
You're using the wrong operator for "and"
Additionally, you're putting parentheses around string literals for no obvious reason, reducing readability. So what you really want is:
if (textBox2.Text == "admin" && textBox1.Text == "admin")
Note that other answers have suggested using || instead of && - that would be an OR condition, which would show a result of "Right" if either of the textboxes had a value of admin. I suspect that's not what you want.
if (textBox1.Text == "admin" && textBox2.Text == "admin")
Label.Text = "right";
else
Label.Text = "wrong";
&& is the boolean AND operator. || is the boolean OR operator.
Check the MSDN page on C# Operators.
You're looking for || (conditional or) or && (conditional and).
The other name for conditional operators is "short-circuiting", because they only evaluate the second condition if they need to. In other words, with a && b, when a is false, the entire expression must be false, so the expression b is not evaluated. This is significant when b has side effects, or when a implies whether it is safe to evaluate b. Examples:
if (MethodA() && MethodB()) //...
Here, MethodB is called only when MethodA returns true.
if (o != null && o.Equals(p)) //...
This is safe (and common), because it saves us from the NullReferenceException when o is null.
You can also use the non-short-circuiting versions of these operators (| and &) with boolean expressions, but this is so rare that most programmers will read it, at first glance, as a mistake; it's better to be more explicit if you want the code always to evaluate both expressions.
if(textBox2.Text == "admin" && textBox1.Text == "admin")
{
//both admin
}
private void Label_Click(object sender, EventArgs e)
{
if ((textBox2.Text == "admin") || (textBox1.Text == "admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
}
You need to use the "and" operator which is "&&" in C#.
if (textBox1.Text == ("admin")) && (textBox2.Text == ("admin))
Your expression is incorrect. The correct syntax is
if (A && B) { ... }
So in your case it should be
if(textBox1.Text.Equals("admin") && textBox2.Text.Equals("admin")) { ... }
You may want to read up a bit on Boolean algebra if this logic is confusing you.
Note the other changes we've all suggested as well - you had extra brackets and should be using Equals() for string comparison as well.
Seems like you need a simple or? Use the double vertical pipe ||
private void Label_Click(object sender, EventArgs e)
{
if (textBox2.Text == ("admin") || textBox1.Text == ("admin"))
{
Label.Text = "right";
}
else
{
Label.Text = "wrong";
errorProvider1.SetError(errorprovider, "Wrong Username or Password");
}
}

Is there a better method to structure this if statement

It just seems a mess to me, my mind tells me there has to be a better way.
I have 6 controls on a web page.
if (printer_make_1.Text != "" && printer_model_1.Text != "" && printer_make_2.Text != "" && printer_model_2.Text != "" && printer_make_3.Text != "" && printer_model_3.Text != "")
{
// Do something
}
What is the best/most efficient way to do this?
You can refactor into a method, if you want to improve the readability or use the same logic elsewhere:
public Boolean AllControlsHaveAValue() {
return (printer_make_1.Text != ""
&& printer_model_1.Text != ""
&& printer_make_2.Text != ""
&& printer_model_2.Text != ""
&& printer_make_3.Text != ""
&& printer_model_3.Text != "");
}
Then just ask:
if (AllControlsHaveAValue()) {
// do something
}
Restructuring starts with your data: avoid printer_make_1, printer_make_2, ...
class PrinterData
{
public string Make { get; set; }
public string Model { get; set; }
}
PrinterData[] printers = new PrinterData[3]; //or use a List<>
printers[0] = new PrinterData { Make = "PH", Model = "1A" };
...
if (printers.All(p => ! (p.Make == "" || p.Model == "")) )
...
if(new[] { printer_make_1, printer_model_1 ...}.All(l => l.Text != string.Empty)
{
//do something
}
You might want to split it up to be more readable:
var labels = new[] { printer_make_1, printer_model_1 ... };
if(labels.All(l => l.Text != string.Empty))
{
//do something
}
I normally put that test into a method and call that to make the if easier to read
private boolean AreAllPrinterFieldsFilled()
{
return (printer_make_1.Text != ""
&& printer_model_1.Text != ""
&& printer_make_2.Text != ""
&& printer_model_2.Text != ""
&& printer_make_3.Text != ""
&& printer_model_3.Text != "");
}
Then in the if:
if (AreAllPrinterFieldsFilled)
{
// Do something
}
There are lots of ways to accomplish this - none of them are elegant. Do what is most readable to you (and those who may come behind you).
I would probably take this approach:
string makeText = String.Concat(printer_make_1.Text, printer_make_2.Text, printer_make_3.Text);
string modelText = String.Concat(printer_model_1.Text, printer_model_2.Text, printer_model_3.Text);
if (makeText.Length != 0 && modelText.Length != 0)
{
// Do something
}
if (!Enumerable.Range(1, 3)
.Any(i => ((TextBox)FindControl("printer_make_" + i)).Text == "" ||
((TextBox)FindControl("printer_model_" + i)).Text == "") {...}
It allows you to later expand the number of printer makes and models, but isn't as strong typed.
private bool CheckAllEmpty(params TextBox[] textBoxes)
{
return textBoxes.All(tb => tb.Text != null);
}
private void Foo()
{
...
if (CheckAllEmpty(tb1, tb2, tb3))
{
mbox("tb1, tb2 and tb3 are all empty");
}
else
{
mbox("tb1, tb2 or tb3 isn't empty");
}
...
}

Categories

Resources