So I am working on a school lab, and I am having a hell of a time with something that should be fairly basic. I have a series of buttons and 2 text-boxes. I have 1 method that all buttons go through and get passed to a new method to determine the instructions needed.
From the new method it calculates and returns the value.
Code looks like this, only using 1 button and its associated if statement in the other method.
public void PassControlDataOnClick(object sender, EventArgs e)
{
string toCall = "";
string szLeft = box_L_Input.Text;
string szRight = box_R_Input.Text;
decimal dLeft = Convert.ToDecimal(szLeft);
decimal dRight = Convert.ToDecimal(szRight);
if (sender.ToString() == " ")
{
toCall = "ADD";
}
decimal dAnswer = MathCalc(dLeft, dRight, toCall);
string szAnswer = dAnswer.ToString();
string szEquation = $"{szLeft}{" "}{((Control)sender).Text}{" "}{szRight}{" = "}{szAnswer}";
lbl_Output.Text = szEquation;
}
public decimal MathCalc(decimal dL, decimal dR, string toCall)
{
decimal dA = 0.0m;
if (toCall == "ADD")
{
dA = dL dR;
}
return dA;
}
Every time I run this, the output I get is from the line decimal dA = 0.0m; I need it to be the return value but for the life of me I can't figure out where I went wrong.
CodePudding user response:
If you step through this code in a debugger, you will see that the if (sender.ToString() == " ")
line is stepped over.
Further more, you can run sender.ToString()
in the debugger's Immediate Window and see that it returns System.Windows.Forms.Button, Text:
(assuming your sender is a normal button with the text
.
In other words, this if check has no hope of ever doing what you want. Since you know the sender
will be a Button, you can cast it to a Button class and get the Text
value out to see if it's indeed the
button:
if (((Button)sender).Text == " ")
{
toCall = "ADD";
}