Today I've read something on the msdn page and then I tried it.
I've defined two event handlers for a text box
this.txtDetailRateOfExchange.Validating +=
new System.ComponentModel.CancelEventHandler(this.ValidateExchangeRate);
this.txtDetailRateOfExchange.Validated += new System.EventHandler(this.ValidatedExchangeRate);
There exist an order for those events and the Validating-event can either change the value of the text field without any problems (double firing) and the event can be canceled. So I've written the following code.
private void ValidateExchangeRate(System.Object sender, CancelEventArgs e)
{
decimal exchangeRate;
try {
exchangeRate = Decimal.Parse(txtDetailRateOfExchange.Text);
txtDetailRateOfExchange.Text = exchangeRate.ToString("N",numberFormatInfo);
txtDetailRateOfExchange.BackColor = Color.Empty;
} catch (Exception) {
txtDetailRateOfExchange.BackColor = Color.Red;
e.Cancel = true;
}
}
The result is a very gently error message.
The textbox is marked red and requires the focus permanently until the error has been removed.
Advantage: We do not need a specific error message in this case and no translations for it.
I suggest that we shall use this technique more frequently ...