user42348
user42348

Reputation: 4319

Validation-Textboxes allowing only decimals

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?

Upvotes: 8

Views: 45803

Answers (9)

Ryan Alford
Ryan Alford

Reputation: 7594

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

Upvotes: 23

Rushabh Master
Rushabh Master

Reputation: 490

try this with asp:RegularExpressionValidator controller

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

Upvotes: 0

luchezco
luchezco

Reputation: 231

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 CurrentCulture object as it could be another character depending on where in the world you are.

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 KeyPress event of the TextBox:

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

Upvotes: 4

lianaent
lianaent

Reputation: 11

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

Upvotes: 0

Toprak
Toprak

Reputation: 293

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

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

Upvotes: 1

Codemunkeee
Codemunkeee

Reputation: 1613

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

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

Upvotes: 1

Rahimi
Rahimi

Reputation: 96

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

Upvotes: 1

particle
particle

Reputation: 3350

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

Upvotes: 0

RvdK
RvdK

Reputation: 19800

How about using the example from 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)

Upvotes: 0

Related Questions