I have a string array.
I need to display buttons based on if the selected item is in the array.
I need to know how to tell the program if "(array.NOT Contains("string"))".
Please can anybody help me??
Thanks in advance
My code:
List<string> activationids = new List<string>();
foreach (ModuleActivation moduleactivation in activationid)
activationids.Add(moduleactivation.ActivationID);
string gvselectActID = GridView1.SelectedRow.Cells[1].Text;
if (activationids.Contains(gvselectActID))
{
activateInsert.Visible = true;
activateUpdate.Visible = false;
deactivate.Visible = true;
}
else if (activationids."NOT" Contains(gvselectActID))
{
activateInsert.Visible = false;
activateUpdate.Visible = true;
deactivate.Visible = false;
}
else
{
activateInsert.Visible = false;
activateUpdate.Visible = false;
deactivate.Visible = false;
}
}
Change:
else if (activationids."NOT" Contains(gvselectActID))
to
else if (!activationids.Contains(gvselectActID))
Or even simpler
bool containsItem=activationids.Contains(gvselectActID);
activateInsert.Visible = containsItem;
activateUpdate.Visible = !containsItem;
deactivate.Visible = containsItem;
The ! means "NOT". So you have to place it in front of the expression you need to negate;
!activationids.Contains("blahblah");
However, it's quite clear that if activationids.Contains("blahblah") is false, you are gonna go into the second case. Also, currently, your third block (... else { ...) will never be hit.
There are two very straightforward ways to do this:
Not the result of the bool function call:
if(!activationids.Contains(gvselectActID))
Check the result and compare it to false
if(activationids.Contains(gvselectActID) == false)
However, you are checking if it contains it in the first if() clause, which means that the first else clause will be fired if it isn't contained. There is no need to check, and there is no way that the third else will ever be fired.
Contains returns true or false, sou you cannot have three branches, you can do just
if (activationids.Contains(gvselectActID)) // it does contain
...
else // it does not contain
...
there are no other possibilities
[joke]
well it could work in this case
http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
[/joke]
This will be enough:
if (activationids.Contains(gvselectActID))
{
// Goes here if condition is true
activateInsert.Visible = true;
activateUpdate.Visible = false;
deactivate.Visible = true;
}
else
{
// Goes here if condition is false
activateInsert.Visible = false;
activateUpdate.Visible = true;
deactivate.Visible = false;
}
There are no other possible options - there can't be a third branch.
This makes no sense:
if(booleanCondition)
{}
else if (!booleanCondition)
{}
else
{}
As by definition, if the booleanCondition is false, the else branch will be taken - there is no need to test for it being false.
Related
I have problem with List string. I put 3 values into myCollection
List<string> myCollection = new List<string>();
myCollection.Add(Encoding.Default.GetString(data));
myCollection.Add(Encoding.Default.GetString(data2));
myCollection.Add(Encoding.Default.GetString(data3));
and now i have 3 values : A,B,C
but now i want to block buttons with contains this values :
for (var i = 0; i < myCollection.Count; i++)
{
if (myCollection.Contains(A))
{
this.A.Enabled = false;
}
else if (myCollection.Contains(B))
{
this.B.Enabled = false;
}
else if (myCollection.Contains(C))
{
this.C.Enabled = false;
}
}
After this loop just first button=false. Now loop done 3 times this same try block button A and my question is:
How block other buttons?
Now i get in first loop run:
this.A.Enabled = false;
2nd this.A.Enabled = false;
3rd this.A.Enabled = false;
but i want :
1st : this.A.Enabled = false;
2nd : this.B.Enabled = false;
3rd : this.C.Enabled = false;
You don't need a loop for this. Just use simple if statements without else.
if (myCollection.Contains("A"))
this.A.Enabled = false;
if (myCollection.Contains("B"))
this.B.Enabled = false;
if (myCollection.Contains("C"))
this.C.Enabled = false;
Mainly the else was causing problems for you. If the condition for A was true, then the code for B and C did not run. This is how else works.
Not sure what exactly are you trying to achieve, but your problem here is that you use if..else. If any of the conditions is true, the rest won't be resolved.
To solve your problem just remove the else keywords from your conditions.
Also, the loop is unnecesary when you use Contains.
If you'd insist on the loop, you would have to change the condition a bit, and then the else would be properly used:
for (int i = 0; i < myCollection.Count; i++)
{
if (myCollection[i] == A)
{
this.A.Enabled = false;
}
else if (myCollection[i] == B)
{
this.B.Enabled = false;
}
else if (myCollection[i] == C)
{
this.C.Enabled = false;
}
}
I searched SO and found some posts, but could not get them to work.
Question: How would I loop to the next item in my List Collection (custLoginHist[1] etc)?
List<eCommCustomer.oCustomer> custLoginHist = new List<eComm.oCustomer>();
eCommCustomerDAL.GetCustomerPrevLogin(custLoginHist, oCust);
if (custLoginHist.Count > 0)
{
eCommSecurityFactory oSecFactory = new eCommSecurityFactory();
if (oCust.CustHash == oSecFactory.CreateHash(custLoginHist[0].CustSalt, custLoginHist[0].CustHash))
{
//Password has been used before;
return false;
}
else
{
// Valid password;
return true;
}
}
return true;
}
foreach(eCommCustomer.oCustomer cust in custLoginHist)
{
//Do something with cust here.
}
OR:
for(int i = 0; i != custLoginHist.Count; ++i)
{
eCommCustomer.oCustomer cust = custLoginHist[i];
//Do something with cust here.
}
In this case, we want to return false for any single match, and true otherwise, so:
foreach(eCommCustomer.oCustomer cust in custLoginHist)
if(oCust.CustHash == oSecFactory.CreateHash(custLoginHist[0].CustSalt, custLoginHist[0].CustHash)
return false;
return true;//if we reached here, no matches.
This is a bad idea though, because you've made breaking into the system easier. If I try to set my password to something, and you refuse, I now know that one of your users uses that password. You are much better off letting this case happen, though you should perhaps be blocking some of the more likely offenders ("password", "password1", etc) with a quality check.
List<eCommCustomer.oCustomer> custLoginHist = new List<eComm.oCustomer>();
eCommCustomerDAL.GetCustomerPrevLogin(custLoginHist, oCust);
foreach (var custLogin in custLoginHist)
{
eCommSecurityFactory oSecFactory = new eCommSecurityFactory();
if (oCust.CustHash == oSecFactory.CreateHash(custLogin.CustSalt, custLogin.CustHash))
{
//Password has been used before;
return false;
}
}
return true;
Try something like this, maybe you have to customize your return statements but it should give you an insight how it works.
foreach(var item in yourList)
{
//Iterate;
}
If you want break , you can use : break;
If you want finish you can use : continue;
List<T> implements IEnumerable<T>, so you can just use foreach or if you to be able to edit T in the loop, you can use for.
foreach(var item in custLoginHist)
{
}
Or
for (int i = 0; i < custLoginHist.Count; i++)
{
}
Then if you need to exit out of the loop before it is completed (such as if you have a condition that is true, you can just use break; to exit the loop, or you can return from a loop too if you want to return a value.
You can you loop for this. For example foreach or for:
foreach (var custLogin in custLoginHist)
{
eCommSecurityFactory oSecFactory = new eCommSecurityFactory();
if (oCust.CustHash == oSecFactory.CreateHash(custLogin.CustSalt, custLogin.CustHash))
{
//Password has been used before;
return false;
}
else
{
// Valid password;
return true;
}
}
List<eCommCustomer.oCustomer> custLoginHist = new List<eComm.oCustomer>();
eCommCustomerDAL.GetCustomerPrevLogin(custLoginHist, oCust);
return custLoginHist.Select(c=>oSecFactory.CreateHash(c.CustSalt,c.CustHash))
.Any(x=>x==oCust.CustHash)
Is it better to evaluate bool once but have more code like this
if (klient.Podmioty.PodmiotRodzaj == "Osoba") {
textImie.Enabled = true;
textNazwisko.Enabled = true;
textNazwa.Enabled = false;
} else {
textImie.Enabled = false;
textNazwisko.Enabled = false;
textNazwa.Enabled = true;
}
comparing to this
textImie.Enabled = klient.Podmioty.PodmiotRodzaj == "Osoba";
textNazwisko.Enabled = klient.Podmioty.PodmiotRodzaj == "Osoba";
textNazwa.Enabled = klient.Podmioty.PodmiotRodzaj != "Osoba";
It's a generic question and maybe this little example is micro optimization but I would like to know whether reusing same bool over and over is not considered bad code.
Probably useful note is that klient.Podmioty.PodmiotRodzaj is actually variable from SQL brought by Entity Framework.
Evaluate once and use the results:
var conditionValue = (klient.Podmioty.PodmiotRodzaj == "Osoba");
textImie.Enabled = conditionValue;
textNazwisko.Enabled = conditionValue;
textNazwa.Enabled = !conditionValue;
The first option, less calculation time and no replica of code...
or, option C:
bool value = klient.Podmioty.PodmiotRodzaj == "Osoba";
textImie.Enabled = value;
textNazwisko.Enabled = value;
textNazwa.Enabled = !value;
but definitely not your option B.
The first is the common answer, and the second is hard to read. However, since you're only setting bools to the same as the condition, there's a third option:
bool t = (klient.podmioty.PodmiotRodzaj == "Osaba");
TextImed.Enabled = t;
TextNazwisko.Enabled = t;
TextNazwa.Enabled = !t;
(On phone, so I prob got the variable names wrong) This is debatibly slightly less clear than the first option, but brief (and avoids code forks).
This is probably very simple but I guess I haven't had enough of coffee yet.
I have an array with four values and I want to check if any of them is invalid and then set a boolean value to false, else to true.
bool validDecoding = false;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
}
else
{
validDecoding = true;
}
}
But if the last does not contain invalid, length or bad then validDecoding is set to true but I want it to be false if one or more values are invalid.
Please help?
Thanks in advance.
Include System.Linq namespace and you can do following:
validDecoding = !arrayOfvalues.Any(
value => value.Contains("invalid") || value.Contains("length") || value.Contains("bad"));
bool validDecoding = false;
foreach (string decodedValue in arrayOfvalues)
{
if (!decodedValue.Contains("invalid") && !decodedValue.Contains("length") && !decodedValue.Contains("bad"))
{
validDecoding = true;
break;
}
}
Set valid to true at first, then set it to false in your loop if it's invalid.
bool validDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
break;
}
}
That way it's never set back to true! (you need more coffee ;-) )
Set your validDecoding to 'true' initially, and only reset to false if it breaks.
bool validDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
}
else
{
//Do Nothing
}
}
I like Andrew's answer. If you don't have Linq available, try this option:
// Note: Name boolean variables like they are a question
bool isValidDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
isValidDecoding &= !decodedValue.Contains("invalid")
&& !decodedValue.Contains("length")
&& !decodedValue.Contains("bad");
}
I particularly like this option when your tests contain logging, and you want to find all failures before termination.
I'd be wary of decodedValue.Contains("length") though. Maybe it works in your scenario, but it might give false negatives for other cases, and definitely makes your code less clear. You should double check that there isn't a more unique/indicative value that ensures that you have a bad decoding for those cases.
I am getting an error while assigning a value.
My code is:
protected bool ValidateProfile()
{
bool blnFirstName = false;
bool blnLastName = false;
bool blnEMail = false;
//(error on line below: "The left-hand side of an assignment must be a variable, property or indexer")
ValidateProfile() = false;
if txtFName != ""
blnFName = true;
if txtLName != ""
blnLName = true;
if txtEMail != ""
blnEMail = true;
if (blnFName) && (blnLName) && (blnEMail))
ValidateProfile = true;
}
How do I assign a boolean value to ValidateProfile ?
Thanks
You want
return false;
In C#, we don't assign values to the function name in order to return a value.
If you want to set the return value at a different point in time from when you return from the method, then you should do something like this:
bool retVal; // Defaults to false
if (condition)
retVal = true;
if (otherCondition)
retVal = false;
if (thirdCondition)
retVal = true;
return retVal;
You can't assign a value to a function. You need return false;
As others have pointed out, in C# you use return instead of MyFunction = x. In this scenario, you can assign the result of your final check to a boolean and return it:
bool retVal = (blnFName) && (blnLName) && (blnEMail);
return retVal;
Alternatively, you could just skip the assignment altogether:
return (blnFName) && (blnLName) && (blnEMail);
EDIT: I noticed you are using hungarian notation, which implies that txtFName is a TextBox. Keep in mind that C# doesn't have default properties like VB. If it is a TextBox, it will never equal "", because it's not of type System.String. I'm guessing you actually wanting to evaluate txtFName.Text
Change that last line to:
return false;
Although it seems you're always returning false here. Is there an option to return true?
Just a side note besides all the returns...
You may want to change this:
if txtFName != ""
To check if the String.IsEmptyOrNull(txtFName.Text)
Or at least initialize your variables to either null or String.Empty.
Just an FYI though.
You want to return false
Alright, taking the code you posted:
protected bool ValidateProfile()
{
return !String.IsNullOrEmpty(txtFName) && !String.IsNullOrEmpty(txtLName) && !String.IsNullOrEmpty(txtEMail);
}
Or
protected bool ValidateProfile()
{
bool returnValue = true;
if(String.IsNullOrEmpty(txtFName))
{
returnValue=false;
}
else if(String.IsNullOrEmpty(txtLName))
{
returnValue = false;
}
else if(String.IsNullOrEmpty(txtEMail))
{
returnValue = false;
}
return returnValue;
}
Though you could just return false as soon as you find an invalid field.
Not a C# programmer, but can't you just write:
return (txtFName != "") && (txtLName != "") && (txtEMail != "");
for the body of the function?