Validating a Radio Box - c#

I'm simply trying to check that one of the three radio boxes has been checked, for some reason even when in debug console all boxes '.Selected = false' it is still skipping over my error message. Any help is appreciated.
if ((rdoIndoor.Checked = false ) && ( rdoOut.Checked = false ) && ( rdoSwimming.Checked = false ))
{
MessageBox.Show("Please select an event style");
}

You are using an assignment operator instead of a comparison operator. The = operator is for assignment. Use == for comparison.
Better yet, get rid of your == operator altogether, and use the ! operator, like this:
if ( !rdoIndoor.Checked && !rdoOut.Checked && !rdoSwimming.Checked )
{
MessageBox.Show( "Please select an event style" );
}

The equality operator, used to compare values, is ==
So your code should be:
if ((rdoIndoor.Checked == false ) &&
( rdoOut.Checked == false ) &&
( rdoSwimming.Checked == false ))
......

use double equals signs (rdoIndoor.Checked **==** false) etc
Single '=' means assignment, i. e. from now let 'rdoIndoor.Checked' be false.
Double '==' is logical test.
You probably know that ;)

Related

Why obvious False result of logical AND operation cancels out FOR loop iteration

My question is why this condition in a for loop makes it cancel out iteration, however it seems to me that condition is fulfilled?! If I try with one of two given variables without using AND operator looping works and continues infinitely.
bool a = false;
bool b = false;
for (; a && b == false; )
{
Console.WriteLine("");
}
This condition
a && b == false
means
a && (b == false)
Since && does short circuit evaluation, the first false will result in false for whole expression, and thus there is no need to evaluate second expression.
Also to add, even with a single & (which doesn't perform short circuit evaluation, your complete condition will result in false.
If you want to compare both a and b to false you can do:
a == false && b == false
or
!a && !b
You should also consider using a while loop, if there is no iteration variable involved.
https://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx
Because the == is evaluated before &&, the condition is a && (b == false)
so false.

if (a or b) and c statement

I'm having difficulty with a multiple option if statement.
Version 1 matches all without considering the && .contains("up")
if (
|| drow["ifName"].ToString().ToLower().Contains("vlan")
|| drow["ifName"].ToString().ToLower().Contains("st0")
|| drow["ifName"].ToString().ToLower().Contains("ge-0")
&& drow["ifStatus"].ToString().ToLower().Contains("up")
)
Version 2 matches none.
if ( (
|| drow["ifName"].ToString().ToLower().Contains("vlan")
|| drow["ifName"].ToString().ToLower().Contains("st0")
|| drow["ifName"].ToString().ToLower().Contains("ge-0")
)
&& drow["ifStatus"].ToString().ToLower().Contains("up")
Something I am missing?
Table looks basically like
ifName | ifStatus
vlan.0 | up
st0.1 | up
pp0.0 | up
ge-0/0/0 | down
EDIT:
So the goal is to match only rows that have ifStatus = UP, also changed table to clarify a real example.
What is your intended parse? logical OR (||) and logical AND (&&) are both left-associative and have different operator precedences:
http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx
Logical AND binds more tightly than does logical OR, so, an expression like
A || B || C && D
parses as if it were written
A || B || ( C && D )
If that is your intent, you're good. If not, you'll need to add parentheses as needed to get the desired parse. My suspicion is that your intended parse is more like:
(A || B || C ) && D
But that is not how your original test parses.
As a good general rule, if you're mixing ANDs and ORs in a logical expression, always use parentheses to indicate your intent. Misunderstanding operator precedence in logical expressions is a major source of bugs.
This may not fix your problem, but it should make it easier to see what you're doing, as well as make the list more maintainable:
var matchNames = new[] {"a", "b", "c", "vlan.10"};
if (drow["ifStatus"].ToString().ToLower().Contains("up") //check up first, because it's cheaper
&& matchNames.Any(m => drow["ifName"].ToString().ToLower().Contains(m) )
{
//...
}
You can use linq to do this, for sample, add this namespace:
using System.Linq;
and try this:
string[] items = new[] { "vlan.10", "a", "b", "c" };
if (drop["IfStatus"].ToString().IndexIf("up", StringComparison.OrdinalIgnoreCase) > -1 &&
items.Any(x => drop["IfName"].ToString().IndexOf(x, StringComparison.OrdinalIgnoreCase) > -1)
{
// true...
}
Read about the Turkey Test, it shows why is important using the IgnoreCase method to compare instead Contains.
Using a regex here can simplify the logic.
if((Regex.IsMatch(drow["ifName"].ToString().ToLower(), "[abc]"))
&& (Regex.IsMatch(drow["ifStatus"].ToString().ToLower(), "up")))
{
}
in first case: it produce true if any one of the expression (OR Expression or AND Expression)evaluates to true.
Note : it is similar to if(A || B || C || D && E)
so if any OR Expressionin (A,B,C) evalutes to true or Expression D and E evaluates to true it becomes true.
in second case : it produce true if any one of the OR expressions is true and AND Expression drow["ifStatus"].ToString().ToLower().Contains("up") also must be true as you are using parenthesis pair.
Note : it is similar to if( (A || B || C || D) && (E) )
so if any one of the OR Expression(A,B,C,D) should evaluate to true and also AND expression E must be true to produce the result true.
Try This:
String name=drow["ifName"].ToString().ToLower();
Sting status=drow["ifStatus"].ToString().ToLower();
if ( (name.Contains("vlan.10") || name.Contains("a") || name.Contains("b")
|| name.Contains("c")) && (status.Contains("up")))

How to use multiple conditional operators using C#

I want to use combination of the 2 operators: the && and the || operator using C#. I have 5 variables that I would like to make sure if these conditions are met.
varRequestedDate
varTotdayDate
varExpectedDate
Approval1
Approval2
Here is what I have for my current condition but would like to add other variables adding the OR operator:
if (varRequestedDate != (" ") && varExpectedDate < varTotdayDate)
here is the pseudocode for what I would like to see after the updated version:
(if varRequestedDate is not blank
and varExpectedDate is less than varTotdayDate
and either Approved1 OR Approved2 = Yes)
send email()
i cannot figure out how to do this.
thanks
You just have to add nested parentheses:
if (varRequestedDate != " "
&& varExpectedDate < varTotdayDate
&& (Approved1 == "Yes" || Approved2 == "Yes")
)
sendEmail();
For the sake of readability and expressiveness I would extract the boolean values into meaningfully named variables:
var isDateRequested = varRequestedDate != (" ");
var isDateWithinRange = varExpectedDate < varTotdayDate;
var isApproved = Approved1 == "Yes" || Approved2 == "Yes";
if (isDateRequested && isDateWithinRange && isApproved)
{...}
You can nest logical operators using parentheses (just like arithmetic operators). Otherwise they follow a defined precedence going left to right.
if (
varRequestedDate !=(" ") &&
varExpectedDate < varTodayDate &&
(Approved1==Yes||Approved2==yes))

Compare strings in if statement

Trying to write a piece of code to compare two strings. If either are equal to the textbox then it opens a new winform. I know how to do the winform part.
string CreditCard1 = "Some numbers";
string CreditCard2 = "Some Numbers";
string RFIDCard1 = "E00700000330E44C";
string RFIDCard2 = "E00700000338E539";
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
I get an error from MSVS 2010 saying:
Operator '||' cannot be applied to operands of type 'string' and 'string'
Is there a way to do what I want?
This line is the culprit:
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
Try:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
On a side note, it scares me that you're apparently working with credit card information, but don't know how to compare values in a text box. I really, really hope, for the sake of your customers, that you plan on investigating how to securely manage that information.
There are three problems here:
You cannot compare against multiple values using an OR (||). This is a surprisingly common misconception, but makes no sense to the compiler.
Comparison in C# is done with ==. = is for assignment.
A TextBox is not a string; you need to use its Text property to get or set the text it contains.
So in the end, your if statement should look like this:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1) {
// ...
}
Ok you have 2 issues here, firstly single equals is assignment not comparison and secondly each argument separated by an or needs to be a bool, ie should be
if(CardScan_txtBx == CreditCard1 ||CardScan_txtBx == RFIDCard1)
Could you use else if?
if(CardScan_txtBx == CreditCard1)
{
//Do something
} else if(CardScan_txtBx == RFIDCard1)
{
//Do something
}
The other answers have the correct code, here is an explanation of the why. When you use the || operator, it is expecting an expression on either side to be something that evaluates to a bool (true or false). When you wrote CardScan_txtBx.Text == CreditCard1 || RFIDCard1 you have an statement that evaluates to a bool on the left, CardScan_txtBx.Text == CreditCard1 and you have a statement that evaluates to string on right RFIDCard1 Because a string is not a bool, you get the compile time error. that is why you must repeat the == operator on the right hand side so that you say CardScan_txtBx.Text == RFIDCard1
Try out with following code.....
if (CardScan_txtBx.Equals(CreditCard1) || CardScan_txtBx.Equals(RFIDCard1))
{
//Code
}
Try this:
if (CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
See here: http://msdn.microsoft.com/en-us/library/53k8ybth%28v=vs.71%29.aspx
Not: =
Right: expr1 == expr2
You can also use a List.
List<string> listOfValidStrings = new List<string>();
//Initialise all valid strings.
if(listOfValidStrings.contains(txtbox.text())
{ do something.}

What does this snippet of C# code do?

What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;

Categories

Resources