Rich
Rich

Reputation: 1

C# If Statement with value from field in Table

How do I write this statement to get a value back from the database or table and validate that if the Value = Yes it will return the "Result =10" part. The field is called "ApprovedStatus" the value will either be "No" or "Yes".

Visual Studio Tells me this: "The name 'Yes' does not exist in the current context"

If (ApprovedStatus.Equals = Yes)
{
result = 10;
}

else
{
result = 1;
}

Upvotes: 0

Views: 3955

Answers (6)

tsells
tsells

Reputation: 2771

if (ApprovedStatus.Equals("Yes"))  <-- Case Sensitive
{

}

or

if (ApprovedStatus.ToString().ToUpper() == "YES")
{

}

Upvotes: 0

Stefan Steiger
Stefan Steiger

Reputation: 82276

If ApprovedStatus is of type bool, do:

if (ApprovedStatus) 

Should it be string, do NOT do this

if(ApprovedStatus == "Yes") 

because this will equal false if ApprovedStatus = "yes"

Instead use

if(StringComparer.OrdinalIgnoreCase.Equals(ApprovedStatus,"Yes"))
    result = 10;
else
   result = 1;

Note that if you do

if (ApprovedStatus.ToString().ToUpper().Equals("YES"))

or

if( ApprovedStatus.Equals("whatever",StringComparison.OrdinalIgnoreCase))

it will throw a null reference exception if ApprovedStatus is null.
...which is possible to likely if the value comes from a database.

Upvotes: 1

Achim
Achim

Reputation: 15722

Boolean values in C# are true and false. You should consult a basic C# tutorial, but your check has probably to look like this:

if (ApprovedStatus)
{
   result = 10;
}
else
{
   result = 1;
}

It can be written shorter as:

result = ApprovedStatus ? 10 : 1;

Upvotes: 0

David Hoerster
David Hoerster

Reputation: 28701

Use String.Compare -- it's more efficient.

if(String.Compare(ApprovedStatus, "Yes", true)==0){
 result = 10;
} else {
 result = 1;
}

Upvotes: 0

David
David

Reputation: 73574

Best guess given the limited info available... (Assuming ApprovedStatus is a String)

if(ApprovedStatus == "Yes") 
{ 
   result = 10; 
} 

else 
{ 
   result = 1; 
} 

or

if(ApprovedStatus.Equals("Yes")) 
{ 
   result = 10; 
} 

else 
{ 
   result = 1; 
} 

Upvotes: 0

cdhowie
cdhowie

Reputation: 169143

Try if (ApprovedStatus == "Yes") if it's a string, or if (ApprovedStatus) if it's a bool.

Upvotes: 5

Related Questions