Hi there! I'm fairly new to C# programming.
I am making a program for fun that adds two numbers together, than displays the sum in a message box. I have two numericUpDowns and a button on my form. When the button is pushed I want it to display a message box with the answer.
The problem is, I am unsure how to add the twp values from the numericUpDowns together.
So far, I have this in my button event handler:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.numericUpDown1.Value + this.numericUpDown2.Value);
}
But obviously, it does not work. It gives me 2 compiler errors: 1. The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string) has some invalid arguments 2. Argument '1': cannot convert decimal to 'string'
Thanks!
-
this.numericUpDown1.Value + this.numericUpDown2.Value
is actually evaluating properly to a number, so you're actually very close. The problem is that theMessageBox.Show()
function, needs a string as an argument, and you're giving it a number.To convert the result to a string, add
.ToString()
to it. Like:private void button1_Click(object sender, EventArgs e) { MessageBox.Show((this.numericUpDown1.Value + this.numericUpDown2.Value).ToString()); }
For reference, if you want to do more advanced formatting, you'd want to use
String.Format()
instead ofToString()
. See this page for more info on how to useString.Format()
. -
Try this:
private void button1_Click(object sender, EventArgs e) { MessageBox.Show((this.numericUpDown1.Value + this.numericUpDown2.Value).ToString()); }
It takes the values from the numericUpDown components and adds them to get an object of the type
Decimal
. This is then converted to a String, which MessageBox takes. -
Now that's easy. NumericUpDown.Value has a type of Decimal.
Messagebox.Show()
expects a String. All you need to do isMessageBox.Show((this.numericUpDown1.Value + this.numericUpDown2.Value).ToString());
to convert the result of the addition to a string.
-
That worked! Thanks everybody!
-
This works.
decimal total = this.numericUpDown1.Value + this.numericUpDown2.Value; MessageBox.Show(total.ToString());
MessageBox.Show expects a string as a parameter (that's the first error message).
0 comments:
Post a Comment