Allow only digits plus decimal separator

  • Thread starter Thread starter João Araújo
  • Start date Start date
J

João Araújo

Hello all,

I'm a VB6 programmer, and I'm starting to change basic functions to .NET.
I've seen an example on how to allow only digits on a textbox control, using
the Edit Control Styles on a specific class DigitTextBox (code example
below).
There is a constant that behaves the way I want except that it misses the
decimal separator.
Is there any way to do this, using the same method (on VB6 I used the
keypressed event to filter the keys)?

Thank you.
João Araújo
Private Class DigitTextBox

Inherits TextBox

Public Sub New()

' Get the current style.

Dim style As Integer = _

GetWindowLong(Me.Handle, GWL_STYLE)

' Add ES_NUMBER to the style.

SetWindowLong(Me.Handle, GWL_STYLE, _

style Or ES_NUMBER)

End Sub

' Override the WndProc and ignore the

' WM_CONTEXTMENU and WM_PASTE messages.

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

Const WM_CONTEXTMENU As Int32 = &H7B

Const WM_PASTE As Int32 = &H302

If (m.Msg <> WM_PASTE) And (m.Msg <> WM_CONTEXTMENU) Then

Me.DefWndProc(m)

End If

End Sub

End Class

Private WithEvents DigitTextBox1 As DigitTextBox

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

' Create the DigitTextBox.

DigitTextBox1 = New DigitTextBox

DigitTextBox1.Name = "DigitTextBox1"

DigitTextBox1.Location = New Point(TextBox1.Left, Label3.Top)

DigitTextBox1.Size = TextBox1.Size

DigitTextBox1.TabIndex = 2

DigitTextBox1.Text = ""

DigitTextBox1.Font = TextBox1.Font

Me.Controls.Add(DigitTextBox1)

' Set the numeric style for TextBox2.

' Get the current style.

Dim style As Integer = _

GetWindowLong(TextBox2.Handle, GWL_STYLE)

' Add ES_NUMBER to the style.

SetWindowLong(TextBox2.Handle, GWL_STYLE, _

style Or ES_NUMBER)

End Sub

End Class
 
João Araújo said:
I've seen an example on how to allow only digits on a textbox control,
using the Edit Control Styles on a specific class DigitTextBox (code
example below).
There is a constant that behaves the way I want except that it misses the
decimal separator.
Is there any way to do this, using the same method (on VB6 I used the
keypressed event to filter the keys)?

No, there is no style like 'ES_NUMBER' that will allow the user to enter a
comma. However, note that even 'ES_NUMBER' doesn't prevent the user from
pasting other characters into the textbox. Instead, I suggest to follow the
pattern described in the document referenced below:

Validator Controls for Windows Forms
<URL:http://msdn.microsoft.com/library/en-us/dnadvnet/html/vbnet04082003.asp>
 
May be there is an easier way, but you could use regular expressions too:
i.e.
if regex.ismached(yourstring,"[0-9]([0-9]|\.|,)*")....
 
Thank you for the answers.
This is very good way to me so I can follow.
João Araújo
 
Back
Top