GUI introduction exercise

advertisement
GUI introduction exercise
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal a;
decimal b;
decimal c;
try
{
a = Convert.ToDecimal(txt1.Text);
b = Convert.ToDecimal(txt2.Text);
}
catch (FormatException)
{
MessageBox.Show("Non-numeric data - 0 assumed");
a = 0;
b = 0;
}
c = a + b;
txtResult.Text = Convert.ToString(c);
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnCalculate_MouseHover
(object sender, EventArgs e)
{
txtResult.Text = "Hover";
}
Some questions to consider:
1. Run the starter program. Try the application. Enter valid
numbers in the txt1 and txt2 boxes and verify that addition works.
2. Enter non-numeric data in txt1.
data” MessageBox is displayed.
Verify that the “non-numeric
3. Move the following statement to the line above the try statement.
a = Convert.ToDecimal(txt1.Text);
Try entering numeric data in txt1 and txt2 again and press the
Calculate button. What happens? Try entering non-numeric data
in txt1 and press the Calculate button. What happens? Why?
4. Why do we use object.property (e.g. textbox.Text) rather than the
object id alone in these examples?
5. Move the a=Convert.ToDecimal(txt1.Text); statement back into the
try block.
6. Move the decimal a; statement into the try block. What happens?
Why? (When you are finished with this step, move the decimal a;
statement back to its original position.
7.
The construction
catch (DivideByZeroException) { . . . }
causes the code between the braces to be executed if a
division by zero occurs in the preceding try block. Change
the program to divide a by b and put the result in c.
Check for both invalid numeric data and division by zero
and, in each case, display a MessageBox with an appropriate
message.
8.
You can join a strings and numeric variables using +. Change
the MessageBox messages to display the values of a and b as well
as the message.
9. Respond to the click event of the Join button by joining the two
Strings and placing the result in txtResult.Text.
10.
Add an if statement to btnCalculate_Click to test for a > 1000m.
If a is greater than 1000, display a MessageBox and change a to
1000.
"m" in 1000m indicates that 1000 is a decimal constant.
11.
Notice that txtResult.Text changes if you let the mouse hover
over txt1.Text. How does this work?
Download