Валидация-текстовые поля, допускающие только десятичные дроби - PullRequest
6 голосов
/ 21 января 2010

Я использую следующий код для проверки текстового поля.

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 не работает. Какие изменения я могу внести в работу backspace.

Ответы [ 10 ]

17 голосов
/ 21 января 2010

вот код, который я бы использовал ...

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 голос
/ 05 февраля 2016

Вы можете создать метод, чтобы проверить, является ли это число.

Вместо того, чтобы проверять . в качестве десятичного разделителя, вы должны получить его от объекта 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 событии TextBox:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(!isNumber(e.KeyChar,TextBox1.Text))
        e.Handled=true;
}
1 голос
/ 07 мая 2014

Это коды для десятичных чисел. Если вы также хотите использовать 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);
        }
    }
1 голос
/ 06 декабря 2013

Вот версия Vb.Net для ответа @ Eclipsed4utoo

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
1 голос
/ 21 февраля 2013

создайте компонент, унаследованный от текстового поля, и используйте этот код:

    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);
    }
0 голосов
/ 29 декабря 2016

попробуйте это с 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>
0 голосов
/ 28 октября 2016

Вот версия 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
0 голосов
/ 07 декабря 2014

Я считаю, что это идеальное решение, поскольку оно не только ограничивает текст числами, только начальным знаком минус и только одной десятичной точкой, но и позволяет заменить выделенный текст, если он содержит десятичную точку. Выделенный текст по-прежнему нельзя заменить десятичной точкой, если в невыбранном тексте есть десятичная точка. Он допускает знак минус, только если это первый символ или выделен весь текст.

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;                                                                   
}
0 голосов
/ 21 января 2010

Как насчет использования примера из MSDN ?

Вы используете '.' как десятичный разделитель? если да, то я не знаю, почему вы используете

if (((TextBox)sender).Text.IndexOf(eChar) > -1)
0 голосов
/ 21 января 2010

Вот код из моего приложения. Он обрабатывает еще один случай, как будет связано с выбором

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]+$";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...