- UID
- 658062
- 积分
- 2147
- 精华
- 贡献
-
- 威望
-
- 活跃度
-
- D豆
-
- 在线时间
- 小时
- 注册时间
- 2008-10-22
- 最后登录
- 1970-1-1
|
楼主 |
发表于 2014-6-7 03:12:39
|
显示全部楼层
NumericBox
Specific properties:
- DecimalPlaces: the number of digits displayed in the box after validation (default 0)
- ErrorMsg: the message displayed by the ErrorProvider for incorrect value (default: "Incorrect number").
- Value: the value as double (default 0.0). Setting this value overwrite the Text property. This value may be more accurate than the displayed one.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace ControlLibrary
{
/// <summary>
/// Defines a control that can be used to display or edit a real number (double).
/// </summary>
public class NumericBox : TextBox
{
private double _value;
private ErrorProvider _errorProvider;
private int _decimalPlaces;
protected string _stringFormat;
/// <summary>
/// Set default values.
/// </summary>
public NumericBox()
{
_value = 0;
_errorProvider = new ErrorProvider();
ErrorMsg = "Incorrect number";
SetFormat();
}
/// <summary>
/// Get or set the number of digits diplayed in the box.
/// </summary>
public int DecimalPlaces
{
get { return _decimalPlaces; }
set { _decimalPlaces = value; SetFormat(); }
}
/// <summary>
/// Get or set the ErrorProvider message.
/// </summary>
public string ErrorMsg { get; set; }
/// <summary>
/// Get or set the number value as double (may be more accurate than the displayed one).
/// Updates the Text according to DecimalPlaces.
/// </summary>
public virtual double Value
{
get { return _value; }
set { _value = value; this.Text = _value.ToString(_stringFormat); }
}
/// <summary>
/// Evaluates if the value is a valid real number.
/// If not, cancels the validation and displayd the ErrorProvider icon.
/// </summary>
/// <param name="e">The event data</param>
protected override void OnValidating(CancelEventArgs e)
{
double d;
if (!double.TryParse(this.Text, out d))
{
e.Cancel = true;
this.Select(0, this.Text.Length);
_errorProvider.SetError(this, ErrorMsg);
}
base.OnValidating(e);
}
/// <summary>
/// Updates Text and Value.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnValidated(EventArgs e)
{
_value = Convert.ToDouble(this.Text);
this.Text = _value.ToString(_stringFormat);
base.OnValidated(e);
}
/// <summary>
/// Hide the ErrorProvider icon.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnTextChanged(EventArgs e)
{
_errorProvider.SetError(this, "");
base.OnTextChanged(e);
}
/// <summary>
/// Creates a format string according to DecimalPlaces value.
/// Updates the Format property.
/// </summary>
private void SetFormat()
{
if (DecimalPlaces < 1)
_stringFormat = "0";
else
{
_stringFormat = "0.";
for (int i = 0; i < DecimalPlaces; i++) _stringFormat += "0";
}
}
}
}
|
|