Reputation: 119
So I have a Calculator GUI with:
2 textboxes for user inputted numbers, 1 button for adding these numbers together, and 1 textbox for showing the result
However, I cannot seem to be able to do the coding part of this, here is what I have:
public partial class Calculator : Form
{
public string firstOperand;
public string secondOperand;
public string result;
public Calculator()
{
InitializeComponent();
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void FirstOperandTextBox_TextChanged(object sender, EventArgs e)
{
FirstOperandTextBox.Text = firstOperand;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
SecondOperandTextBox.Text = secondOperand;
}
private void AddButton_Click(object sender, EventArgs e)
{
firstOperand + secondOperand = result;
}
For the addButton part, I am getting the error, "The left hand side of an assignment must be a variable, property, or indexer".
Upvotes: 0
Views: 166
Reputation: 420
There are several problems with your code
You write your statements as you would write the equations in real life, ie 1 + 1 = 2
. But in the code, you have to write it the other way around - you assign value to a variable, so you should have
result = firstOperand + secondOperand;
You try to add together string values. So if you had 1 and 1 in your operands, the result would be 11 and not 2 as you expect.
Assigning the value of the operands in the TextChanged event is unnecessary, and you can simply do the conversion in the buttons OnClick event.
Furthermore, since you only want numbers, and not text, you would be better off using NumericUpDown control, instead of TextBox. That will take care of wrong input for you (wrong input would be if user put some other characters in the TextBox, or empty value). If you use TextBox, you have to do some conversion from string first.
private void AddButton_Click(object sender, EventArgs e) { result = numericFirst.Value + numericSecond.Value; }
private void AddButton_Click(object sender, EventArgs e) { result = numericFirst.Value + numericSecond.Value; lblResult.Text = result.ToString(); }
Upvotes: 1
Reputation: 4413
private void AddButton_Click(object sender, EventArgs e)
{
int first = 0;
int second = 0;
//Use TryParse() method to avoid exceptions while parsing an invalid string
int.TryParse(FirstOperandTextBox.Text, out first);
int.TryParse(SecondOperandTextBox.Text, out second);
//in the left hand side of = operator, there **must** be a variable always.
result = first + second;
ResultTextBox.Text = result.ToString();
}
Upvotes: 0
Reputation: 1141
You want your result to store the final value.
private void AddButton_Click(object sender, EventArgs e)
{
result = (Convert.ToInt32(firstOperand) + Convert.ToInt32(secondOperand)).ToString();
MyResultTextBox.Text=result;
}
Upvotes: 0
Reputation: 47
In AddButton_Click, change firstOperand + secondOperand = result
to firstOperand.Text + secondOperand.Text
Upvotes: 0