Two functions on same MouseClickEvent C# [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm having some difficulty making two separate functions inside the same MouseClick Eventhandler on a checkbox in C# using Winforms.
If the user clicks the checkbox it's supposed to come a warning for the user to verify the action. If the user un-checks the checkbox a different warning will show for the user to verify the action.
My code is the following:
private bool alreadyClicked = false;
private void myCheckbox_MouseClick(object sender, MouseEventArgs e)
{
if (!myCheckbox.Checked && !alreadyClicked)
{
DialogResult d1 = MessageBox.Show("Some text1", "Some title1", MessageBoxButtons.YesNo);
if (d1 == DialogResult.Yes)
{
myCheckbox.Checked = true;
alreadyClicked = true;
}
else
{
myCheckbox.Checked = false;
}
}
if (myCheckbox.Checked && alreadyClicked)
{
DialogResult d2 = MessageBox.Show("Some text2", "Some title2", MessageBoxButtons.YesNo);
if (d2 == DialogResult.Yes)
{
myCheckbox.Checked = false;
alreadyClicked = false;
}
else
{
myCheckbox.Checked = true;
}
}
}
The problem is that the second if-statement checking if the checkbox is checked and if the "alreadyClicked"-variable is true triggers when the user verifies the first action (to check the checkbox), which happens due to the "alreadyClicked"-variable being true before the event closes. I'm stuck and would appreciate any help.
Thanks in advance.

Well let's look at the two if statements.
When the checkbox is first clicked and the first messagebox will be answered with yes, you set the checkbox and the alreadyClicked variable to true. Right afterwards in the second if statement you check if those two values are true. Which they are of course because we just set them to true. Therefore the second if statement will be true and the second message will be displayed.
To prevent this behaviour you could use an else if (myCheckbox.Checked && alreadyClicked) after the first if statement. In that case the second if statement will only be processed, when the first one results to false.
You could also consider if the bool variable alreadyClicked is really adding any value here. As of my understanding it always has the same value as the checkbox itself.

Related

The Code Won't Execute all [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following code:
private void G1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, cost = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Cost"].Value.ToString(), out cost))
{
decimal price = quantity * cost;
G1.Rows[e.RowIndex].Cells["Total"].Value = price.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity))
{
newtotalstock = totalstock - quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
return;
}
decimal avai = 0, newavai = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai - quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
return;
} }
The problem is, it only execute 2 out of 3 the code, I mean, when the newtotalstock is calculated, the code will end.
I try to change the newavai to up above, and the result is the same, it will calculate the newavai and pass the newtotalstock. I dont know why, all the code are correct. Please help
word "return" ends function, if you are using void type method you don't really need to use return, unless you want to quit it at certain point. The code after "return" will never be executed (only exception might be during usage "yield return", but that is another story).
void someMethod()
{
doSomething();
return;
StartWorldWarThree(); //no waries, this will never be executed :)
}
Furethermore you can always make a breakpoint in your code (click on the left border of your window, or just read about it) and then check how your code is being executed :) F10/F11 to make step in your code, F5 to go to next breakpoint or end execution, if there are no more breakpoints.
Taking in count that all conditions are true the return; will stop executing the rest of the code, if you want the 3 if to be executed, remove the return; and place it the last line of the method as
void Method() {
if() {}
if() {}
if() {}
return;
}
Or dont place it at all, because that method is void and does not need it

C# using a message box(yes/no) to restart my game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am creating a minefield style game as a task and I am wondering if there is a quick easy way to restart my game. When the character walks on to a bomb, I have a message box pop up saying 'game over, try again?' with a Yes and No option. I want the No option to close the game and I want the Yes option to restart the game to its original state that it is opened in. Any ideas?
This is the message box code when it executes:
private void checkBomb( int X, int Y)
{
if (bombs[X, Y])
{
this.BackColor = Color.Red;
downBtn.Enabled = false;
upBtn.Enabled = false;
leftBtn.Enabled = false;
rightBtn.Enabled = false;
showBombs();
// Dialog box with two buttons: yes and no.
//
DialogResult result1 = MessageBox.Show("Game Over! Try again?",
"Game Over",
MessageBoxButtons.YesNo);
}
else
{
countBombs(X, Y);
}
}
I think you would be able to do the following:
MessageBoxResult result = MessageBox.Show("Game Over! Try again?",
"Game Over",
MessageBoxButtons.YesNo);
if (result == MessageBoxResult.No)
{
System.Windows.Application.Current.Shutdown();
}
if (result == MessageBoxResult.Yes)
{
//Restart your game
}
According to the MSDN website,
https://msdn.microsoft.com/en-us/library/system.windows.forms.application.restart(v=vs.110).aspx
You can use Restart() method if "Yes" is clicked, and Close() if "No" is clicked

.Net Else Statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
else
Label1.Text = "Invalid Username and/or Password.";
}
Above is a function I'm trying to make happen. For some reason the else statement here isn't being accepted. I don't know why. Any help would be appreciated.
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
Label1.Text = "Invalid Username and/or Password.";
Wrap it with braces, otherwise it'll take only the next immediate line (statement) as part of the condition.
It's a good practice to do that even for a one line if/else because it makes maintenance easier.
else
{
Label1.Text = "Invalid Username and/or Password.";
}
if-else (C# Reference) - MSDN
Both the then-statement and the else-statement can consist of a single
statement or multiple statements that are enclosed in braces
({}). For a single statement, the braces are optional but
recommended.
You have multiple statements in the then (true) part of if statement. Although you have used indentation, but those spaces/indents will not be considered by the compiler. Since you haven't specified {} to define scope of if statement, only a single statement is considered for if scope. Hence the error.
You can fix that by introducing scope with {}. It is also recommended to use {} (explicitly define scope) for single statement , as it makes code easier to understand and less prone to error. You code should be:
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
{
Label1.Text = "Invalid Username and/or Password.";
}
}

Can't stop a timer in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want the timer to stop when the ImageNumber is equal to zero.
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
if (ImageNumber1 < 20)
{
ImageNumber1++
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
}
If I add a return statement after the first if statement the second if statement is disabled.
I want the timer to stop when the ImageNumber is equal to zero.
You appear to already know how to do this, assuming Health_Regen is a Timer then:
Health_Regen.Enabled = false;
Will disable your Timer.
If I add a return statement after the first if statement the second if statement is disabled.
That is to be expected as you are using the return keyword which will prevent anything after it within the same code block from being executed.
Your question does not make exactly what you are asking clear, however, I am assuming from your comment that the second if statement is not executed that you want to update the HealthBar.Image value even if the Timer is disabled? If so then something like below should work for you
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
{
Health_Regen.Enabled = false;
}
else if (ImageNumber1 <= 20)
{
ImageNumber1 += 1;
}
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png";
}
You should just be able to call the Stop method on the timer instance.
if (ImageNumber == 0)
{
Health_Regen.Stop();
}
This is just a guess!.
Replace
if (ImageNumber1 == 0)
with
if (ImageNumber1 >= 20)
Your timer will already stop when ImageNumber1 equals 0, but it just never counts down to 0.
Also if you change ImageNumber1 to 0. It may already be running the timer which will increment it by one and skip the stopper, so pretty much the way you have it coded it's based on luck right now.
The luck happens if you change ImageNumber1 while timer is already running.
Try this:
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
else if (ImageNumber1 < 20)
{
ImageNumber1++;
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
Still the luck may still happen best you can do is stop the timer outside the timer when you make it ImageNumber1 = 0;
Best Fix:
Also a better solution is to fix your program to start at ImageNumber1 = 20 and just keep going down to 0.. when it hits 0 stop the timer.. you shouldn't make it this confusing all you will have to do is rename a few png files in a new order! instead of
1.png now it will be 20.png
2.png now it will be 19.png
and so on and so on..

How to perform different logic based on checkbox being true or false?

I have two sections(primary and secondary) in a form with several textboxes which display information. On the secondary section I've added a checkbox (which when checked) I want to copy the information from the fields on the primary section into the fields on the secondary side. If its unchecked I want it to leave the field as blank.
Here is some sample code to help see what I am trying to do:
The CheckChanged event calls four different methods (each method contains logic for a specific checkbox):
private void CheckBoxCheckedChanged(
{
Method1();
Method2();
Method3();
Method4();
}
When Method4 is called I'd like to process the logic mentioned above if its checked, and leave blank if its not.
private void Method4()
{
if (checkBox4.Checked = true)
{
secondaryTextbox.Text = primaryTextbox.Text;
}
else if (checkBox4.Checked = false)
{
secondaryTextbox.Text = "";
}
}
The issue I'm having is that when I do this once the checkbox is checked, I can no longer 'uncheck' to change the field back to being blank.
What am I doing wrong, or is there a better way to go about this?
I apologize ahead of time if I posted this wrong, this is my first time using SO.
The code you wrote makes an assignment (=) inside the if statement's expression, but this is not what you mean. You should use == if you want to make a comparison. Or even better, just do this instead:
if (checkBox4.Checked)
{
secondaryTextbox.Text = primaryTextbox.Text;
}
else
{
secondaryTextbox.Text = "";
}
As Paolo pointed out the code you tried gives a compiler warning. If you try to never write code that produces warnings you can catch simple errors like this more quickly. There's even an option to treat warnings as errors which you can use.
You need
if (checkBox4.Checked == true)
to check if true, the way you were doing it was always assigning it the value "true"
You are doing assignment when you mean to be testing
use this
if (checkBox4.Checked == false)
or better this
if (false == checkBox4.Checked)
or even better this
if ( ! checkBox4.Checked)
instead of this
if (checkBox4.Checked = false)
You have a very small problem in your code:
you are using = instead of ==
also it is better to define an array of check-box and text-box instead of func1,func2,func3,func4
You are using a single "=" to test of the checkbox is checked.
THis has the effect of setting the checkbox state.
Use "==", as in
if (checkBox4.Checked == true)
or in fact, much better:
if (checkBox4.Checked)

Categories

Resources