winform input 輸入數值(可以小數,負數)

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; } } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章