validation – 文本框仅允许小数

我使用以下代码validation文本框。

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = SingleDecimal(sender, e.KeyChar); } public bool SingleDecimal(System.Object sender, char eChar) { string chkstr = "0123456789."; if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack) { if (eChar == ".") { if (((TextBox)sender).Text.IndexOf(eChar) > -1) { return true; } else { return false; } } return false; } else { return true; } } 

问题是Constants.vbBack显示错误。如果我没有使用Constants.vbBack,退格不是workimg。我可以做什么改变工作退格。任何人都可以帮忙吗?

这是我要用的代码……

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { // allows 0-9, backspace, and decimal if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46)) { e.Handled = true; return; } // checks to make sure only 1 decimal is allowed if (e.KeyChar == 46) { if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1) e.Handled = true; } } 

创建从文本框inheritance的组件并使用以下代码:

  protected override void OnKeyPress(KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') { e.Handled = true; } // only allow one decimal point if (e.KeyChar == '.' && Text.IndexOf('.') > -1) { e.Handled = true; } base.OnKeyPress(e); } 

这是@ Eclipsed4utoo答案的Vb.Net版本

 If (((Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 8 And Asc(e.KeyChar) <> 46)) Then e.Handled = True Exit Sub End If ' checks to make sure only 1 decimal is allowed If (Asc(e.KeyChar) = 46) Then If (sender.Text.IndexOf(e.KeyChar) <> -1) Then e.Handled = True End If End If 

您可以创建一种方法来检查它是否为数字。

而不是检查. 作为小数分隔符,您应该从CurrentCulture对象获取它,因为它可能是另一个角色,具体取决于您所在的世界。

 public bool isNumber(char ch, string text) { bool res = true; char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator); //check if it´sa decimal separator and if doesn´t already have one in the text string if (ch == decimalChar && text.IndexOf(decimalChar) != -1) { res = false; return res; } //check if it´sa digit, decimal separator and backspace if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back) res = false; return res; } 

然后你可以调用TextBoxKeyPress事件中的方法:

 private void TextBox1_KeyPress(object sender, KeyPressEventArgs e) { if(!isNumber(e.KeyChar,TextBox1.Text)) e.Handled=true; } 

如何使用MSDN中的示例?

你使用’。’ 作为十进制分隔符? 如果是这样,我不知道你为什么使用

 if (((TextBox)sender).Text.IndexOf(eChar) > -1) 

这里有一些代码来自我的应用 它将处理另一个与选择相关的案例

 protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == '\b') return; string newStr; if (SelectionLength > 0) newStr = Text.Remove(SelectionStart, SelectionLength); newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1)); double v; //I used regular expression but you can use following. e.Handled = !double.TryParse(newStr,out v); base.OnKeyPress(e); } 

这里是正则表达式,如果喜欢使用它们而不是那种简单的类型解析

 const string SIGNED_FLOAT_KEY_REGX = @"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$"; const string SIGNED_INTEGER_KEY_REGX = @"^[+-]?[0-9]*$"; const string SIGNED_FLOAT_REGX = @"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$"; const string SIGNED_INTEGER_REGX = @"^[+-]?[0-9]+$"; 

这个代码为小数。 如果你也想使用float,你只需要使用double insteat int它将自动删除最后错误的字符串

 private void txt_miktar_TextChanged(object sender, TextChangedEventArgs e) { if ((sender as TextBox).Text.Length < 1) { return; } try { int adet = Convert.ToInt32((sender as TextBox).Text); } catch { string s = ""; s = (sender as TextBox).Text; s = s.Substring(0, s.Length - 1); (sender as TextBox).Text = s; (sender as TextBox).Select(s.Length, s.Length); } } 

我相信这是一个完美的解决方案,因为它不仅将文本限制为数字,仅限于前导减号,只有一个小数点,但如果包含小数点,则允许替换所选文本。 如果未选择的文本中有小数点,则所选文本仍然不能用小数点替换。 只有当它是第一个字符或者选择了整个文本时,它才允许使用减号。

 private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e) { if (numeric) { // only allow numbers if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back)) return true; } else { // allow a minus sign if it's the first character or the entire text is selected if (e.KeyChar == '-' && (txt.Text == "" || txt.SelectedText == txt.Text)) return false; // if a decimal point is entered and if one is not already in the string if ((e.KeyChar == '.') && (txt.Text.IndexOf('.') > -1)) { if (txt.SelectedText.IndexOf('.') > -1) // allow a decimal point if the selected text contains a decimal point, that is the // decimal point replaces the selected text return false; else // don't allow a decimal point if one is already in the string and the selected text // doesn't contain one return true; } // if the entry is not a digit if (!Char.IsDigit(e.KeyChar)) { // if it's not a decimal point and it's not a backspace then disallow if ((e.KeyChar != '.') && (e.KeyChar != Convert.ToChar(Keys.Back))) { return true; } } } // allow only a minus sign but only in the beginning, only one decimal point, any digit, a // backspace, and replace selected text. return false; } 

这是一个允许负十进制数字的vb.net版本,防止复制和粘贴,同时确保负号不在文本的中间或小数点不在文本的开头

Public Sub Numeric(textControl As Object,e As KeyPressEventArgs)

  Dim Index As Int32 = textControl.SelectionStart Dim currentLine As Int32 = textControl.GetLineFromCharIndex(Index) Dim currentColumn As Int32 = Index - textControl.GetFirstCharIndexFromLine(currentLine) Dim FullStop As Char FullStop = "." Dim Neg As Char Neg = "-" ' if the '.' key was pressed see if there already is a '.' in the string ' if so, dont handle the keypress If e.KeyChar = FullStop And textControl.Text.IndexOf(FullStop) <> -1 Then e.Handled = True Return End If 'If the '.' is at the begining of the figures, prevent it If e.KeyChar = FullStop And currentColumn <= 0 Then e.Handled = True Return End If ' if the '-' key was pressed see if there already is a '-' in the string ' if so, dont handle the keypress If e.KeyChar = Neg And textControl.Text.IndexOf(Neg) <> -1 Then e.Handled = True Return End If 'If the '-' is in the middle of the figures, prevent it If e.KeyChar = Neg And currentColumn > 0 Then e.Handled = True Return End If ' If the key aint a digit If Not Char.IsDigit(e.KeyChar) Then ' verify whether special keys were pressed ' (ie all allowed non digit keys - in this example ' only space and the '.' are validated) If (e.KeyChar <> Neg) And (e.KeyChar <> FullStop) And (e.KeyChar <> Convert.ToChar(Keys.Back)) Then ' if its a non-allowed key, dont handle the keypress e.Handled = True Return End If End If End Sub Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress Numeric(sender, e) End Sub 

尝试使用asp:RegularExpressionValidator控制器