问题描述
我需要一个文本框:
(1)仅接受数字作为字符。
(1) only accepts digits as characters.
( 2)在用户输入数值时,会自动继续使用逗号格式化数字值。
(2) automatically continues to format numeric values with commas as the user types into it.
例如,
1 becomes 1.00
10 becomes 10.00
100 becomes 100.00
1000 becomes 1,000.00
10000 becomes 10,000.00
100000 becomes 1,00,000.00
如何实现?
推荐答案
在用户键入 时格式化数字通常效果不佳。您应该为此使用MaskedTextBox。 Internet上有很多关于如何过滤KeyPress的代码,因此只能输入数字。
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.
理智的方法是对待具有基本技能的用户,例如键入数字并轻轻提醒她,错了。为此进行Validating事件。这也是格式化数字的最佳时间。在您的项目中添加一个新类,并粘贴以下代码:
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;
}
编译。将新的NumberBox控件从工具箱的顶部拖放到窗体上。还要在窗体上放置一个ErrorProvider,以便可以以适度的方式报告键入错误,并设置新控件的ErrorProvider属性。 (可选)修改Fraction属性。您可以订阅ValueChanged事件,以了解何时修改了值。
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.
这篇关于如何使文本框仅接受数字并用逗号格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!