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
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I end a method with logic in another method? It seems return only works in the method it is in.
private void BeAmazing (int number) {
HandleNumber(number);
Debug.Log("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
}
Your inner function should return a result indicating whether it was successful in doing whatever it is supposed to do, like this:
private void BeAmazing (int number) {
if (!HandleNumber(number)) {
Debug.Log("number is 3 or less");
}
}
private bool HandleNumber(int number) {
if (number > 3) {
return true;
}
return false;
}
I have to guess a bit, as your description was insufficient. But I guess that FunctionA calls FunctionB - propably in some form of loop - and that in certain cases things that happen in FunctionB should also cancel the loop in FunctionA, thus ending FunctionA.
The primary way for this is throwing Exceptions. Exceptions will just plow through all brackets, until they find catch block. And the last one is in the Framework itself. There are two articles on excetpion handling, that a link often.
However one rule the mention is to not throw exceptions in situations that are not exceptional. And this case might not be exceptional. Well, for those cases there are out parameters:
void FunctionA(){
bool continueLoop = true;
while(continueLoop){
FunctionB(out continueLoop);
}
}
void FunctionB(out bool continueLoop){
//Set the bool, for out parameters this will change it back in FunctionA
continueLoop = false;
}
Of course there is also the way more common case of Recursion, where FunctionA and FunctionB are either the same, or B keeps calling itself. This is often better then using a loop like this.
Robert McKee has got the question covered, but here are two little examples how
HandleNumber could communicate with BeAmazing using an exception.
Please note that an if is the simplest solution here. The examples below are just to show another possibility.
Example 1
Task: Print the message if number is 3 or less without modifying BeAmazing.
private void BeAmazing (int number)
{
HandleNumber(number);
Debug.WriteLine("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
throw new Exception("Number is > 3");
}
}
public static void Main()
{
var p = new Program();
try
{
p.BeAmazing(5);
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
}
p.BeAmazing(3);
Number is > 3
number is 3 or less
Example 2
Task: Make BeAmazing print different messages if number is >3 or not without modifying the signature of HandleNumber.
private void BeAmazing (int number)
{
try
{
HandleNumber(number);
Console.WriteLine($"This number is amazing");
}
catch( Exception ex )
{
Console.WriteLine(ex.Message);
}
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
throw new Exception("Number is 3 or less");
}
public static void Main()
{
var p = new Program();
p.BeAmazing(5);
p.BeAmazing(3);
}
This number is amazing
Number is 3 or less
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
When i press "buttonTotal" i need it to add fuel prices together. I have lblDailyPrice, lblTotalLitresEntered and i have 3 buttons "unleaded"; "Diesel"; "Premium"... any help as to how i can achieve this?
private void btnTotal_Click(object sender, EventArgs e)
{
try
{
if(btnUnleaded_Click)
{
}
else if (btnDiesel_Click)
{
}
else if (btnPremium_Click)
{
}
}
catch
{
}
}
I would advise making the "unleaded", "Diesel", "Premium" options RadioButtons instead of Buttons and bind them under a container like Panel. So, when the user presses the "buttonTotal" the program will check which RadioButton is checked and then calculate the corresponding value.
private void btnTotal_Click(object sender, EventArgs e)
{
double totalPrice = 0;
if(unleadedRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * unleadedValue;
}
else if (dieselRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * dieselValue;
}
else if (premiumRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * premiumValue;
}
}
I'm assuming your using Windows Forms. I have linked relevant documentation on how to accomplish this task. With just a tiny bit of reading, it should be easy. Good luck and welcome to StackOverflow!.
Get the prices from the labels.
Convert those strings into a number type with a decimal.
Then just do the math on the resulting variables.
Example:
var total = Convert.ToDecimal(lblDailyPrice.Text) * Convert.ToDecimal(lblTotalLitresEntered.Text);
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..
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a Code Editing control that can format text somewhat like Visual Studio,till now i have implemented syntax highlighting and autocompletion but i want to format text in nested curly braces.For example:Consider a for loop,
for(int i=0;i<=10;i++)
{
Function_One(); //This should be a tab away from first brace
Function_Two(); //So with this
if(a==b) //So with this
{ //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
} //This should be four tabs away from first brace
}
now what i want is that this should look something like this,
for(int i=0;i<=10;i++)
{
Function_One();
Function_Two();
if(a==b)
{
MessageBox.Show("Some text");
}
}
I have already tried Regular Expressions but at some point they fail to match,so i tried to match it with code but code cannot match very deeply nested code or is very hard to implement
,so is there any way to achieve this,and one more thing i am doing all this in Winforms control RichTextBox using C#.
This is by no means a simple feat, I am unaware of any tools or plugins that you would be able to take advantage of, my only recommendation is to research Monodevelop's implementation of this.
See MonoDevelop's github for details.
I think the best way to implement this would be to create some global variables for your form:
private int _nestedBracketCount = 0;
private const string TabString = " ";
private const int TabSpaces = 4;
And then handle all of it in a KeyPressed event handler for the rich text box:
private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
var currentLength = richTextBox1.Text.Length;
if (e.KeyChar == '{') {
// need to increment bracket counter
_nestedBracketCount++;
} else if (e.KeyChar == '}') {
// remove last #(TabSpaces) characters from the richtextbox
richTextBox1.Text.Remove(currentLength - TabSpaces);
_nestedBracketCount--;
richTextBox1.AppendText("}");
e.Handled = true;
} else if (e.KeyChar == (char)13) {
// append newline and correct number of tabs.
var formattedSpaces = string.Empty;
for (var i = 0; i < _nestedBracketCount; i++)
formattedSpaces += TabString;
richTextBox1.AppendText("\n" + formattedSpaces);
e.Handled = true;
}
}
I think this should provide you with a halfway decent starting point.
In the button 8 click event i did:
private void button8_Click(object sender, EventArgs e)
{
if (buttonLockMode == true)
{
trackBar1.Enabled = true;
button8.ForeColor = Color.Red;
button8.Enabled = false;
textBox1.Text = "Frame Number : " + trackBar1.Value;
this.trackBar1.Select();
textBox3.Enabled = true;
textBox4.Enabled = true;
wireObjectAnimation1 = new WireObjectAnimation(this, wireObject1);
int currentFrameIndexRight = trackBar1.Value;
wireObjectCoordinates1 = new WireObjectCoordinates() { FrameNumber = currentFrameIndexRight };
WireObjectCoordinatesCloneFrame();
List<WireObjectCoordinates> temp = wireObjectAnimation1.CoordinatesList;
temp.Add(wireObjectCoordinates1);
//wireObjectAnimation1.CoordinatesList.Add(wireObjectCoordinates1);
//WireObjectCoordinatesCloneFrame();
}
else
{
button8.ForeColor = Color.Black;
}
}
Phoog i used the same idea of temp List.
And in the wireObjectanimation i did:
private List<WireObjectCoordinates> _coordinateslist = new List<WireObjectCoordinates>();
public List<WireObjectCoordinates> CoordinatesList
{
get { return _coordinateslist; }
}
And still when i put a breakpoint on the get line the _coordinateslist and CoordinatesList both empty.
First throws if there's no element that satisfies the predicate. It follows that there's most likely no item in the _coordinatesList whose FrameNumber is equal to currentFrameIndex.
Try this: Change catch to catch (Exception e) and when execution enteres the catch block, use the debugger to examine the exception. Or, set your debugger to break on handled exceptions, which will also give you the opportunity to examine the exception.
Once you've determined whether the hypothesis is true, that is, that there's no element in the sequence that satisfies the predicate, you can proceed to the next step, which is to determine why there's no element that satisfies the predicate: either your expectation is wrong, or the code that is supposed to satisfy the expectation is wrong.
This is a great example of why you should never use catch { } in your code.
It would also be helpful if you stick to code conventions. An identifier like _coordinatesList would typically be a private field; WireObjectCoordinatesList would typically be a public property. You have it backwards, which is confusing.
Regarding the breakpoint in the list getter:
I put a breakpoint on the get and it stop there when i click on button8 But now the List _coordinatesList is empty. If i put the breakpoint on Form1 button8 click event i see the List is containing the point coordinates but when im in wireObjectanimation class the List is empty.
Consider this code:
private List<string> _words = new List<string>();
public List<string> Words { get { return _words; } }
And this calling code:
void AddAWord(string word)
{
this.Words.Add(word);
}
That calling code is equivalent to this:
void AddAWord(string word)
{
List<string> temp = this.Words;
temp.Add(word);
}
In other words, the property getter first returns the list to AddAWord, and then AddAWord calls Add on the list. Thet's most likely the reason why the list doesn't yet contain anything when you put the breakpoint in the property getter.
EDIT
I did not mean to suggest that adding a temp variable would solve your problem. Rather, the temp variable is intended to clarify why the problem is occurring. Adding the temp variable does not change the meaning of the code. In fact, the C# compiler may well create the temp variable implicitly.
Perhaps I misunderstood what you've done and what you're expecting, but to me it looks like your expectations are incorrect. In other words, you've put your breakpoint on the wrong line.
Consider:
1 private List<WireObjectCoordinates> _coordinateslist = new List<WireObjectCoordinates>();
2 public List<WireObjectCoordinates> CoordinatesList
3 {
4 get { return _coordinateslist; } // <<< your breakpoint here
5 }
6
7 private void button8_Click(object sender, EventArgs e)
8 {
9 if (buttonLockMode == true)
10 {
11 // ...
12 List<WireObjectCoordinates> temp = wireObjectAnimation1.CoordinatesList; // <<< my breakpoint here
13 temp.Add(wireObjectCoordinates1);
14 }
15 else
16 {
17 // ...
Now step through the code. You have a breakpoint on line 4. I am adding a breakpoint at line 12. We hit line 12 first. Hit F11. Execution moves to line 4, which is your breakpoint. Note that the list is empty. Of course it is empty, because we haven't reached line 13 yet.
Hit F11 a couple of times to step through the property getter. The execution point returns to line 12. The temp variable is still null. Hit F11 once more to assign the property value to the temp variable. Execution moves to line 13.
Hit F11 once more. This calls the Add method. Now the list contains one element.
My point is that this sequence of instructions is the same regardless of whether there's a temp variable or not. Consider a single-line expression, like this:
wireObjectAnimation1.CoordinatesList.Add(wireObjectCoordinates1);
The following steps happen, in this order:
Determine the object referred to by wireObjectAnimation1
Call the CoordinatesList getter on that object
Call the Add method on the the object returned by the CoordinatesList getter in the previous step
Your breakpoint is in the second step; Add is called in the third step; the list is therefore empty when you hit the breakpoint.