3

I have a Masked Textbox and I want it to be able to accept a double value. There shouldn't be a limit of sorts to the amount of characters which can fit before/after the decimal point.

I realise there are other ways of doing this such as overriding key input events or using a numeric up down but I'm just asking whether its possible using a mask.

I've tried 9999999999.99999999 - but its giving me a lot of problems - such as:

1 2 3 4 . 6 being accepted as input (spaces included) and me not being able to drop the . wherever I want it.

Aabela
  • 1,408
  • 5
  • 19
  • 28
  • The NumericUpDown control is the preferred alternative. I know you know this, but it kind of makes this question irrelevant. – Cody Gray - on strike Aug 09 '12 at 08:15
  • Don't like the useless space next to the end of the NumericUpDown after you strip away the up/down buttons. I was hoping that something designed to accept a mask would have a nice simple answer. – Aabela Aug 09 '12 at 08:21

1 Answers1

0

This is a straightforward solution. There is no need for a mask. Usually the mask is not the answer to all applications. I wrote the initial solution. If you want it, you can combine it with a mask.

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AddHandlerTextBoxDouble(TextBox1)
End Sub

Public Sub AddHandlerTextBoxDouble(ByVal TextBoxMe As Object)
    Dim TextBox As New TextBox
    TextBox = CType(TextBoxMe, TextBox)
    AddHandler TextBox.KeyPress, AddressOf TextBox_KeyPress
    AddHandler TextBox.TextChanged, AddressOf TextBox_TextChanged
End Sub

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    ValidatingNumber(e, sender)
End Sub

Public Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim TextBox As New TextBox
    TextBox = CType(sender, TextBox)
    If Not IsNumeric(TextBox.Text) And TextBox.Text <> "." Then
        TextBox.Text = ""
    End If
End Sub

Public Sub ValidatingNumber(ByVal e As Object, ByVal control As Object)
    Try
        If CType(control, TextBox).Text.IndexOf(".") > -1 And e.KeyChar = "." Then
            e.KeyChar = ""
        End If
        If (Asc(e.KeyChar) < 58 And Asc(e.KeyChar) > 47) Or e.KeyChar = vbBack Or e.KeyChar = "." Then
            e.KeyChar = e.KeyChar
        Else
            e.KeyChar = ""
            Try
                CType(e, System.Windows.Forms.KeyPressEventArgs).Handled = True
            Catch ex As Exception
            End Try
        End If
    Catch ex As Exception
        MsgBox("ValidatingNumber")
    End Try

End Sub


End Class