In: Computer Science
private void btnCalculate_Click(object sender, System.EventArgs e) { decimal weightInPounds = 0m; try { weightInPounds = Convert.ToDecimal(txtPounds.Text); if (weightInPounds > 0) { decimal weightInKilos = weightInPounds / 2.2m; lblKilos.Text = weightInKilos.ToString("f2"); } else MessageBox.Show("Weight must be greater than 0.", "Entry error"); txtPounds.Focus(); } catch(FormatException) { MessageBox.Show("Weight must be numeric.", "Entry error"); txtPounds.Focus(); } } (Refer to code example 7-1.) If the user enters 118 in the text box and clicks the Calculate button, what does the code do?
/* when calculate button clicks it saves lblKilos.Text with value 53.64 */
/* BELOW DOWN THERE IS COMMENTS FOR EVERY STATEMENT */
private void btnCalculate_Click(object sender,
System.EventArgs e)
{ decimal weightInPounds = 0m;
try {
weightInPounds =
Convert.ToDecimal(txtPounds.Text); // returns 118m
if
(weightInPounds > 0) { // true 118m > 0
decimal weightInKilos = weightInPounds / 2.2m;
// 118m/2.2m = 53.63636363636363
lblKilos.Text = weightInKilos.ToString("f2"); //
53.64 // round to 2 decimal places
}else
MessageBox.Show("Weight must be greater than
0.", "Entry error");
txtPounds.Focus(); // it highlights textbox
} catch(FormatException) {
MessageBox.Show("Weight must be numeric.", "Entry error");
txtPounds.Focus();
}
}