public partial class UCNumberBox : UserControl
{
public UCNumberBox()
{
InitializeComponent();
}
private bool _IsDecimal = true;
/// <summary>
/// 是否为小数,默认为小数
/// </summary>
public bool IsDecimal
{
get { return _IsDecimal; }
set
{
_IsDecimal = value;
if (!value && this.tbValue.Text.IndexOf('.') >= 0)
{
tbValue.Text = tbValue.Text.Substring(0, tbValue.Text.IndexOf('.'));
tbValue.SelectionStart = tbValue.Text.Length;
}
if (value && _Precision == 0)
{
_Precision = 2;
}
}
}
private int _Precision = 2;
public int Precision
{
get { return _Precision; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(Precision), "精度不能小于0");
}
_Precision = value;
if (value == 0)
{
_IsDecimal = false;
}
}
}
private void tbValue_KeyPress(object sender, KeyPressEventArgs e)
{
// 先排除非需要的字符
if (!char.IsDigit(e.KeyChar)
&& e.KeyChar != '.'
&& e.KeyChar != '-'
&& e.KeyChar != '.'
&& e.KeyChar != '\b')
{
e.Handled = true;
}
if (e.Handled || e.KeyChar == '\b')
{
return;
}
// 去掉0开头的证书,类似:0123
if (tbValue.Text == "0" && char.IsDigit(e.KeyChar))
{
if (e.KeyChar != '0')
{
tbValue.Text = e.KeyChar.ToString();
tbValue.SelectionStart = 1;
}
e.Handled = true;
}
// 负号只能出现在第一位
else if (tbValue.Text.Length > 0 && (e.KeyChar == '-'))
{
e.Handled = true;
}
// 排除 -0123这种
else if (tbValue.Text == "-0" && char.IsDigit(e.KeyChar))
{
if (e.KeyChar != '0')
{
tbValue.Text = "-" + e.KeyChar.ToString();
tbValue.SelectionStart = 2;
}
e.Handled = true;
}
//整数,不能出现小数点
if (!IsDecimal && e.KeyChar == '.')
{
e.Handled = true;
}
// 小数
else if (IsDecimal)
{
if (e.KeyChar == '.')
{
// 替换小数点开头的=》0.
if (tbValue.Text.Length == 0)
{
tbValue.Text = "0.";
tbValue.SelectionStart = 2;
e.Handled = true;
}
// 不能重复插入小数点
else if (tbValue.Text.IndexOf('.') >= 0)
{
e.Handled = true;
}
IsInputD = !e.Handled;
}
if (!e.Handled && tbValue.Text.IndexOf('.') >= 0)
{
// 校验小数位数
var ss = tbValue.Text.Split('.');
if (ss[1].Length >= Precision)
{
e.Handled = true;
}
}
}
}
private bool IsInputD = false;
private void tbValue_TextChanged(object sender, EventArgs e)
{
// 在中间插入小数时,需要保证小数位数不超出指定精度
if (IsInputD)
{
IsInputD = false;
var ss = tbValue.Text.Split('.');
if (ss[1].Length > Precision)
{
var format = "".PadLeft(Precision, '0');
tbValue.Text = double.Parse(tbValue.Text).ToString("0." + format);
tbValue.SelectionStart = tbValue.Text.Length;
}
}
}
}
winform input 输入数值(可以小数,负数)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.