locked
Allowing Only 1 Decimal "." in Textbox

    Question

  • I am having trouble making it where if the user types more than one "." decimal they get a error msg or whatever. Mainly having problems coding the Character "."
                 Thanks
    Wednesday, June 28, 2006 12:11 AM

Answers

  • I don't know, I prefer to write my own code to control this sort of thing, but I've learned it's easier to point people to the built in control. 

    I'm just using google to bring up the MaskedTextBox docs on MSDN.

    http://windowssdk.msdn.microsoft.com/en-us/library/kkx4h3az.aspx

    Looks like the Mask property is what you want, I'd guess that "0000.00" allows up to four digits before and two after the only decimal point in the number. 

    Wednesday, June 28, 2006 1:03 AM

All replies

  • I don't know what you mean by coding the character '.' ? A maskededitbox is the easiest solution to your problem.

     

    Wednesday, June 28, 2006 12:39 AM
  • Well what I'm trying to do is make it where you cant put 2.2.2 and only allow the one decimal 2.2 Dont know if maskedtextbox will do that?
    Wednesday, June 28, 2006 12:52 AM
  • Yes, that is precisely what it is for.

     

    Wednesday, June 28, 2006 12:54 AM
  • I geuss I should say how do you limit a maskedtextbox to only accept 1 decimal?
        Thank for help so far..

    Wednesday, June 28, 2006 12:59 AM
  • I don't know, I prefer to write my own code to control this sort of thing, but I've learned it's easier to point people to the built in control. 

    I'm just using google to bring up the MaskedTextBox docs on MSDN.

    http://windowssdk.msdn.microsoft.com/en-us/library/kkx4h3az.aspx

    Looks like the Mask property is what you want, I'd guess that "0000.00" allows up to four digits before and two after the only decimal point in the number. 

    Wednesday, June 28, 2006 1:03 AM
  • Nah,    FormatNumber ("textbox1, 4)  4 being the amount of zeros need to find out how to code a period into the code but dont know how to refer to period key in Vb2005

    Wednesday, June 28, 2006 1:10 AM
  • The period key is just that, a period,  "." - what's wrong with that ?

     

    Wednesday, June 28, 2006 1:12 AM
  • I just created a VB.NET project, added a MaskedTextBox, set the mask to 0000.00 in the designer, ran it, and it works great.  It actually stops you from typing the ., it provides it.

    The alternative is to handle the KeyPress event of a normal text box and do something like this :

    private void OnNumericKeyPress(object sender, KeyPressEventArgs e)

    {

    if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')

    {

    TextBox tb = sender as TextBox;

    int cursorPosLeft = tb.SelectionStart;

    int cursorPosRight = tb.SelectionStart + tb.SelectionLength;

    string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);

    string[] parts = result.Split('.');

    if (parts.Length > 1)

    {

    if (parts[1].Length > 2 || parts.Length > 2)

    {

    e.Handled = true;

    }

    }

    }

    else

    {

    e.Handled = !Char.IsControl(e.KeyChar);

    }

    }

    I've provided the C# code in case the VB.NET code converter I use doesn't emit code that works, but according to that, the VB code is :

       Private  Sub OnNumericKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
                If Char.IsNumber(e.KeyChar) Or e.KeyChar = "."c Then
                    Dim tb As TextBox =  sender as TextBox
     
                    Dim cursorPosLeft As Integer =  tb.SelectionStart
                    Dim cursorPosRight As Integer =  tb.SelectionStart + tb.SelectionLength
     
                    Dim result As String =  tb.Text.Substring(0,cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight)
     
                    Dim parts() As String =  result.Split("."c) 
     
                    If parts.Length > 1 Then
                        If parts(1).Length > 2 Or parts.Length > 2 Then
                            e.Handled = True
                        End If
                    End If
                Else
                    e.Handled = Not Char.IsControl(e.KeyChar)
                End If
            End Sub

    '----------------------------------------------------------------
    ' Converted from C# to VB .NET using CSharpToVBConverter(1.2).
    ' Developed by: Kamal Patel (http://www.KamalPatel.net)
    '----------------------------------------------------------------

    Now you see why I recommend the MaskedTextBox :-)

    Wednesday, June 28, 2006 1:33 AM
  • hmm if (input.text.Contains("."))
    {
        e.Handled = true; ???
    }
    Daniel K Ward
    Friday, November 07, 2008 9:29 PM
  •  
    1     Private Sub ntb_TextChanged(ByVal sender As ObjectByVal e As System.EventArgs) Handles ntb.TextChanged  
    2       If Me.Check Then 
    3         Dim txt$ = Me.ntb.Text  
    4         If txt = Nothing Then 
    5  
    6         ElseIf txt.Length = 0 Then 
    7  
    8         ElseIf txt = "0" Then 
    9  
    10         ElseIf txt.EndsWith(","Or txt.EndsWith("."And lString.Recognize.isStrictInt(lString.Missing.remlchr(txt)) Then 
    11  
    12         ElseIf (lString.c.CountForeigners(txt, lString.constants.numbers) > 1) Then 
    13           Dim bkp As New Support.cTextBox.TextSelection(Me.ntb)  
    14           If lString.Recognize.isDouble(txt) Then 
    15             Dim val# = lString.Easy.toDouble(txt)  
    16             Me.ntb.Text = val.ToString  
    17             bkp.TryApply(Me.ntb)  
    18           Else 
    19             Me.ntb.Text = "" 
    20           End If 
    21         ElseIf ((Strings.InStr(txt, ".") > 0) Or Strings.InStr(txt, ",") > 0) And txt.EndsWith("0"Then 
    22  
    23         Else 
    24           Dim bkp As New cTextBox.TextSelection(Me.ntb)  
    25           Dim val# = lString.Easy.toDouble(txt)  
    26           Me.ntb.Text = val.ToString  
    27           bkp.TryApply(Me.ntb)  
    28         End If 
    29       End If 
    30     End Sub 
    Annotations:
    #2: Check says that autocorrection of textbox is enabled
    #10: IsStrictInt determines string to or not to consist of only numbers
    #10: remlchr removes last char in hope it can be dot or comma
    #12: c.CountForeigners returns count of nonumeric characters in string if used with "012..89" const
    #13: Class TextSelection provides mechanism to storing selectionStart and selectionLength and recover it or supply some intelligent behaviour if recovery is not possible
    #14: IsDouble Checks string against all possible formats of double string representation (dots, commas, E+)
    #15: ToDouble uses same mechanism as IsDouble to parse string to double, possibly synonym, maybe extension to Double.Parse
    #17: recovering maximum of cursor and selection information destroyed by hard assignation of text value

    You can find this as part of my Support library, namely Support.cTextBox.DoubleBox, which is so called control behaviour extension class, which instantiated for some control modifies its behaviour and optionally provides Value# property. Support is and will be free and open source. You can ispire what is to be done if you want to do it yourself, from this code, or you can simply try to use my DLL. But DLL is about 2 megs, having lot of different stuff inside...Anyway I wouldn't support you to use whole support.dll, for it contains thousands of functions which are not fully annotated. And few which are not debugged at all. You can also extract only DoubleBox with related functions from it :)
    Saturday, November 08, 2008 10:20 PM
  • My C# contribution is : Only one decimal separator in the textbox + controlled number of decimal digits,

    -------------------------

    using System.Globalization;

    ...

    private void textBox_KeyPress(object sender, KeyPressEventArgs e)

     

            {

                 CultureInfo ci = System.Globalization.CultureInfo.CurrentUICulture;

                char cDecimalSeparator = ci.NumberFormat.CurrencyDecimalSeparator[0]; // "." or "," depending of systems config.

                bool bDecimalSeparatorFound = (0 <= this.textBox.Text.IndexOf(cDecimalSeparator ));

     

                if ( (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && !(e.KeyChar==cDecimalSeparator ))

                    || (e.KeyChar == cDecimalSeparator && bDecimalSeparatorFound )) // only one decimal separator

                {

                    // unauthorized KeyChar or double decimal separator received : skipping this one

                    e.Handled = true;

                }

     

                // only "ci.NumberFormat.CurrencyDecimalDigits" numbers allowed after decimal separator

                if (char.IsDigit(e.KeyChar) && bDecimalSeparatorFound )

                {

                    int nDecimalDigits = this.textBoxAmount.Text.Length 

                        - this.textBox.Text.LastIndexOf(ci.NumberFormat.CurrencyDecimalSeparator) - 1;

     

                    if (nDecimalDigits >= ci.NumberFormat.CurrencyDecimalDigits)

                        e.Handled = true; // doesn't comply to system configuration : skipping this one

                }

        

               // Everything seems okay, let base class handle this one!

                base.OnKeyPress(e);

            }

     

     

     

    Hope this helps :)

     







    Wednesday, March 30, 2011 1:16 PM