验证 - 文本框仅允许小数

时间:2010-01-21 11:00:30

标签: c# winforms

我正在使用以下代码验证文本框。

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,则backspace不是workimg。我可以对backspace进行哪些更改。任何人都可以帮忙吗?

10 个答案:

答案 0 :(得分:17)

这是我将使用的代码......

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;
    }
}

答案 1 :(得分:1)

创建一个继承自textbox的组件并使用以下代码:

    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);
    }

答案 2 :(得分:1)

这是@ 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

答案 3 :(得分:1)

此代码为小数。如果你也想使用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);
        }
    }

答案 4 :(得分:1)

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

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

public bool isNumber(char ch, string text)
{
    bool res = true;
    char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

    //check if it´s a 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´s a digit, decimal separator and backspace
    if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
        res = false;

    return res;
}

然后,您可以在KeyPress的{​​{1}}事件中调用该方法:

TextBox

答案 5 :(得分:0)

这是我的应用程序中的一些代码。它处理一个与选择相关的案例

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);
}

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

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]+$";

答案 6 :(得分:0)

如何使用MSDN中的示例?

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

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

答案 7 :(得分:0)

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

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;                                                                   
}

答案 8 :(得分:0)

这是一个允许负十进制数字的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
        ' (i.e. 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

答案 9 :(得分:0)

使用asp:RegularExpressionValidator控制器

尝试此操作
<asp:RegularExpressionValidator ID="rgx" 
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic"  ValidationGroup="lnkSave"></asp:RegularExpressionValidator>