Formatting a number while the user is typing in general works very poorly. You should use a MaskedTextBox for that. Plenty of code about on the Internet that shows how to filter KeyPress so only digits can be entered. Most of it is trivially defeated by using the Paste command.
The sane way is to treat the user capable of basic skills like typing a number and gently remind her that she got it wrong. The Validating event is made for that. Which is also the perfect time to format the number. Add a new class to your project and paste this code:
using System;
using System.ComponentModel;
using System.Windows.Forms;
public class NumberBox : TextBox {
public NumberBox() {
Fraction = 2;
}
public ErrorProvider ErrorProvider { get; set; }
[DefaultValue(2)]
public int Fraction { get; set; }
public event EventHandler ValueChanged;
public decimal Value {
get { return this.value; }
set {
if (value != this.value) {
this.value = value;
this.Text = Value.ToString(string.Format("N{0}", Fraction));
var handler = ValueChanged;
if (handler != null) ValueChanged(this, EventArgs.Empty);
}
}
}
protected override void OnValidating(CancelEventArgs e) {
if (this.Text.Length > 0 && !e.Cancel) {
decimal entry;
if (decimal.TryParse(this.Text, out entry)) {
if (ErrorProvider != null) ErrorProvider.SetError(this, "");
Value = entry;
}
else {
if (ErrorProvider != null) ErrorProvider.SetError(this, "Please enter a valid number");
this.SelectAll();
e.Cancel = true;
}
}
base.OnValidating(e);
}
protected override void OnEnter(EventArgs e) {
this.SelectAll();
base.OnEnter(e);
}
private decimal value;
}
Compile. Drop the new NumberBox control from the top of the toolbox onto your form. Also drop an ErrorProvider on the form so typing mistakes can be reported in modest way, set the ErrorProvider property of the new control. Optionally modify the Fraction property. You can subscribe the ValueChanged event to know when the value was modified.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…