I'm new here and I have a problem (I think the solution is simple, but I can't solve this problem alone). I have to throw a few checkbox on userform (that is simple) but when I write something like this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("co nie tak");
}
always get "ok1" MsgBox...
Any ideas what I'm doing wrong? Thanks for helping.
The if statement will always go into the first block that is true. So if checkbox1 is checked you will always get "ok1". You can never get into the second block ( "ok2" ) because if it is true, the first check would also be true.
I think you want to switch your checks:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
You may also be looking to build up your string by adding to it. The += means add to the end of the string.
My example code is just an example, since I don't really know what you are trying to do, but it might give you some ideas.
if (checkBox1.checked )
{
mic.HTMLBody = "1) Example1";
}
if ( checkBox2.checked )
{
mic.HTMLBody += "<br>"""2) Example2";
if ( ComboBox2.Text == "Pan" )
{
mic.HTMLBody += "<br>Pana";
}
}
from the code i see if checkbox1.checked is true then "ok1" should display and the second an third evaluations would never be evavluated. if checkbox1.checked is false then only the third option would be evaluated and the second option should never be evaluated at all. Should be more like:
if (checkBox1.Checked)
{
if (checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("ok1");
}
}
else
{
MessageBox.Show("co nie tak");
}
As it is currently written, it is impossible for it to enter the else if, because whenever the else if condition is true, the if condition is also true.
It goes from up to down, the first that is true is entered and the rest are ignored.
Instead you should switch their place as follows:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
A little unclear what you really want shown, but if you want it to first show ok1 and then ok2 then you can do this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
if(checkBox2.Checked) {
MessageBox.Show("ok2");
//MessageBox.Show("ok1 ok2"); //If you want to show them both at the same time
}
}
else
{
MessageBox.Show("co nie tak");
}
I tried this one on a Console and it might be the logic you need. The inline comments will give you a bit of insight of what is doing what:
check1 = true;
check2 = true;
if (check1)
{
if (check2)
{
// Prints if BOTH check1 and check2 are TRUE
Console.WriteLine("ok2");
}
else
{
// Prints if ONLY check1 is TRUE
Console.WriteLine("ok1");
}
}
else
{
// Prints if BOTH check1 and check2 are FALSE
Console.WriteLine("co nie tak");
}
bool Check = checkBox1.Checked;
bool Check2 = checkBox2.Checked;
if (Check == true && Check2 == true)
{ MessageBox.Show("ok 1 & 2"); }
if (Check == true)
{ MessageBox.Show("ok 1"); }
if (Check2 == true)
{ MessageBox.Show("ok 2 "); }
else
{ MessageBox.Show("Not Checked"); }
Related
My question is a bit hard to describe so I have written a hypothetical code (nonfunctioning) down below and I wonder if there is a similar alternative in C#:
if (Red == true)
{
i -= 3;
}
else if (Yellow == true)
{
i -= 2
}
then
{
list.Clear();
}
else{}
A "then" function of sorts that both if statements follow if one where to execute. The use of this would simply be so that I do not need to do in this case a list.Clear(); in every if statement.
No there is no syntax construct like your then but you can create a method that clear the list and accept and returns the value to decrement
private int ClearAndDecrementBy(int decrement)
{
list.Clear();
return decrement;
}
and call it as
if(Red)
{
i -= ClearAndDecrementBy(3);
}
else if(Yellow)
{
i -= ClearAndDecrementBy(2);
}
else
{
}
Not really sure that there is any advantage though. The list should be declared at the global class level and this is never a good practice if it is needed only to make it work in this way. So, adding the call to list.Clear inside the if blocks seems more clear and it won't do any harm
Try this:
if(Red == true)
{
i -= 3;
}
else if(Yellow == true)
{
i -= 2
}
else
{
}
if(Red == True || Yellow == true) //You can add more like: Blue == true
{
list.Clear();
}
You could get rid of the "then" statement from your pseudo code and add the following line to the end of everything.
if (Red || Yellow)
{
list.Clear();
}
Try this:
if (Red || Yellow)
{
i = Red ? -3 : -2;
list.Clear();
}
else { }
I got a little problem. I got a if statement which says if Session isn't equal 3, then do something, and if that isn't true, then do something else. My problem is just, that it isn't working proberly.
I've already tried:
1)
if (Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
2)
if (Session["userrank"].ToString() != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
3)
if ((string)Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
4)
if (((string)Session["userrank"]) != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
but none of them seems to work. And i have already checked if there's a Session called userrank that is getting the result 3.
sorry for the "stupid" question. I'm kind of new to C# & ASP.net.
Best Regards,
Anton
Your code sets pnlAdmin.Visible = false; if whatever is in Session["userrank"] is not 3.
It sets pnlAdmin.Visible = true; if whatever is in Session["userrank"] is 3.
You said it is 3; therefore, the panel should be visible. And that seems to be what is happening.
I've been thinking about this problem for some time, but i just can't think of a solution without having to write duplicate code. The problem in part c# and part pseudo-code:
bool test = true;
if (test == true)
{
if(first condition) {code}
}
else
{
if(different condition) {same code as above)
}
I have to use this part in a performance intensive part of my program and i'd have to transfer 3 big parameters, which is why i'd rather not use a method.
Is there another way to solve this?
if((test && firstCondition) || (!test && differentCondition)) {
//code
}
if ((test && first_condition) || (!test && different_condition)) {
callSomeFunction();
}
I'd do it like this:
// create an inline function to capture the
Action workAction = () => { //work; }
bool test = true;
if (test == true)
{
if(first condition) {workAction(); }
}
else
{
if(different condition) {workAction(); )
}
Depending on the complexity of the conditions, this approach can sometimes help:
bool doBigCall = false;
if (test1)
{
if (test2)
{
doBigCall = true;
}
else
{
// ...
}
}
else
{
// ...
}
if (doBigCall)
{
// write the big bit of code just once
}
I have a logic like below and i have a counter
if(condition1 == true)
{
// do something
if (counter==1)
{
// break and go to last else statement
}
}
else if (condition2==true)
{
if (counter == 2)
{
// break and go to last else statement
}
// do something
}
else
{
// do this
}
how do i use break in this logic ?
i tried putting goto tag for else but apparently it is not valid . and i want to avoid switch as there is too much logic.
counter will be 2 in second if else loop and if counter = 2 then first if and secong if else should execute if counter=3 then first if second if else third if else should execute ans so on –
Note: Question was changed, this answer is meanwhile incorrect!
You can change the if/else if to include the counter. Then you don't need a break or goto:
if (condition1 && counter != 1)
{
// do something
}
else if (condition2 && counter != 2)
{
// do something
}
else
{
// do this
}
use something like
if (condition1 && ( counter != 1 || counter != 2 || .... counter!= n )
{
// do something
}
else if (condition2 && (counter != 2 || .. || counter!= n )
{
// do something
}
and so on
else
{
// do this
}
Apart from the fact that a break statement doesn't jump outside an if condition, your code could be
refactored in a more simple way (just pretend that the closed brace after the first if it's only a typo)
if(condition1 ==true && counter != 1)
{
do something
}
else if (condition2==true && counter != 2)
{
do something
}
else
{
do this
}
I suspect that your algorithm could be entirely redesigned, but without more context that's impossible to know.
In the meantime, you can refactor your final else clause into a separate method. You don't actually need to use break (which isn't valid in an if statement anyway), with judicious use of else.
private void MyMethod()
{
if(condition1)
{
// do something
if (counter==1)
{
MyOtherMethod();
}
}
else if (condition2)
{
if (counter == 2)
{
MyOtherMethod();
}
else
{
// do something
}
}
else
{
MyOtherMethod()
}
}
private void MyOtherMethod()
{
// Do what was in your final else clause.
}
Prior to your question edits that moved the `do something' in the first if clause to before the counter check, this would have worked too:
Assuming your various "do something" statements were different things:
if (condition1 && counter != 1)
{
// Do something.
}
else if (condition2 && counter != 1)
{
// Do something.
}
else
{
// Do something else.
}
Just put the logic in the last else block in a seperate function which you can call whenever / wherever you want.
Don't. Using a break and continue in such a big loop adds complexity and clutters your logic.
If a loop is getting too big, use one or more well-named function calls within the loop instead.
bool myCondition = false;
if(condition1 ==true)
{
if (counter==1){myCondition = true;}
// do something
}
else if (condition2==true)
{
if (counter==1){myCondition = true;}
// do something
}
// so on
if(myCondition)
{
// do this
}
I'm trying to replicate the Mastermind game within c# and have hit a hurdle, so to speak. The problem I'm facing is at the stage where player 2 guesses which 3 checkboxes are correct from the 6 available. (8 rows for 8 attempts/lives at guessing). The code I have works when player 2 guesses the correct checkboxes, however when the incorrect checkboxes are selected and the "guess" button is clicked nothing happens. I have a second if statement to check this but obviously something must be wrong. The code for the button click event is:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
CheckBox[] checkBoxArray = new CheckBox[]
{ checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
for (int i = 0; i < checkBoxArray.Length; i++)
{
if (checkBoxArray[i].Checked)
boxesChecked++;
}
if (boxesChecked > 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Only 3 are allowed.");
else if (boxesChecked < 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Please choose 3.");
if (checkBox1.Checked == cb1)
if (checkBox2.Checked == cb2)
if (checkBox3.Checked == cb3)
if (checkBox4.Checked == cb4)
if (checkBox5.Checked == cb5)
if (checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!",
"Game Won");
if (MessageBox.Show("Would you like to play again?",
"Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
if (checkBox1.Checked != cb1)
if (checkBox2.Checked != cb2)
if (checkBox3.Checked != cb3)
if (checkBox4.Checked != cb4)
if (checkBox5.Checked != cb5)
if (checkBox6.Checked != cb6)
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
}
}
Ok, let's go. There a few things to review at your code:
1. How many checkbox are checked?
Let's use a little lamba to make that for a little bit prettier:
boxesChecked = checkBoxArray.Where<CheckBox>(x => x.Checked).Count();
2. If the user doesn't have checked 3 checkboxes, let's show the message and leave the method!
It's a little bit simplified too, you may wish to change it:
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
3. Verify the result
Let's change those if a little bit. Notice the main else condition (player lost!):
if (checkBox1.Checked == cb1
&& checkBox2.Checked == cb2
&& checkBox3.Checked == cb3
&& checkBox4.Checked == cb4
&& checkBox5.Checked == cb5
&& checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
else
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
Please note that I'm not saying that this is the best design for a game, I'm just pointing out a few things to change on your code.
UPDATE
Based on spender's comment, let's review your method. Please, check it out:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
List<CheckBox> AllTheCheckBoxes = new List<CheckBox> { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
boxesChecked = AllTheCheckBoxes.Where<CheckBox>(x => x.Checked).Count();
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
if (AllTheCheckBoxes.Any<CheckBox>(x => x.Checked != Convert.ToBoolean(x.Tag)))
{
MessageBox.Show("Unlucky, Guess Again!");
AllTheCheckBoxes.ForEach(x => x.Visible = false);
return;
}
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
Notice that I'm using the Tag property. It's an arbitrary string, that developer may use for any purpose. Here I'm expecting that the correct value (true or false) is stored at this property.
UPDATE 2
Regarding OP comment about finding all the checkboxes (looks like its 48 total).
You can use the following statement (understand it and improve it to your needs).
List<CheckBox> AllTheCheckBoxes = this.Controls.AsQueryable().OfType<CheckBox>().Where(x => x.Tag != null).ToList();
Your check for an incorrect value appears to be inside the braces of the if statements for when the user guesses correctly.
In other words, it won't ever be hit. You need to break it out of the braces so it runs.
Like others said, all those nested ifs are going to hurt you in the end. Consider cleaning up that bit so you can understand what's happening better.