C# 验证文本框只允许小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2108616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:33:50  来源:igfitidea点击:

Validation-Textboxes allowing only decimals

c#winforms

提问by user42348

I am using following code for validating textbox.

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

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

Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?

问题是 Constants.vbBack 显示错误。如果我没有使用 Constants.vbBack,退格键不起作用。

采纳答案by Ryan Alford

here is the code I would use...

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

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

回答by particle

Here some code from my app. It handle one more case as will related to selection

这是我的应用程序中的一些代码。它处理与选择有关的另一种情况

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

here regex expression if like to use them instead of that easy type parsing

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

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

回答by RvdK

How about using the example from MSDN?

如何使用MSDN 中的示例?

Are u using the '.' as decimal seperator? if so than I don't know why you are using

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

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

回答by Rahimi

create a component inherited from textbox and use this code:

创建一个从文本框继承的组件并使用以下代码:

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

回答by Codemunkeee

Here is a Vb.Net version for @Eclipsed4utoo's answer

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

回答by Toprak

This codes for decimals. If you want to use float also, you just use double insteat int And it will be delete automaticaly last wrong charachters

这是小数的代码。如果你也想使用浮点数,你只需使用 double instate 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);
        }
    }

回答by lianaent

I believe this is the perfect solution as it not only confines the text to numbers, only a leading minus sign, and only one decimal point, but it allows the replacement of selected text if it contains a decimal point. The selected text still cannot be replaced by a decimal point if there is a decimal point in the non-selected text. It allows a minus sign only if it's the first character or if the entire text is selected.

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

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

回答by luchezco

You can make a method to check if it's a number.

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

Instead of checking for the .as a decimal separator you should get it from CurrentCultureobject as it could be another character depending on where in the world you are.

.您应该从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;
}

Then you can call the method in the KeyPressevent of the TextBox:

然后您可以在KeyPress发生以下情况时调用该方法TextBox

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

回答by Lord Amen

Here is a vb.net version that allows negative decimal figure, prevent copy and paste while making sure the negative sign is not in the middle of the text or the decimal point not at the beginning of the text

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

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

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

回答by Rushabh Master

try this with asp:RegularExpressionValidatorcontroller

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>