1

I'm making a calculator in VB, but I'm stuck with trying to make the textbox only receive floats, I can do it by having the textbox be cleared after every letter is put in, but that's quite a lot of overkill, I've added my code in, I hope you can help me ^.^

Private Sub Button1_TxtChng(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles TextBox1.KeyDown, TextBox2.KeyDown
    Dim num1, num2 As String

    num1 = TextBox1.Text
    num2 = TextBox2.Text


    If IsNumeric(TextBox1.Text) Then
        'The compare code should be a function'
        If num1 = num2 Then
            Me.Label1.BackColor = Color.Orange
        ElseIf num1 < num2 Then
            Me.Label1.BackColor = Color.Red
        Else
            Me.Label1.BackColor = Color.LightGreen
        End If
    Else
        TextBox1.Clear()
    End If
    If IsNumeric(TextBox2.Text) Then
        'The compare code should be a function'
        If num1 = num2 Then
            Me.Label1.BackColor = Color.Orange
        ElseIf num1 < num2 Then
            Me.Label1.BackColor = Color.Red
        Else
            Me.Label1.BackColor = Color.LightGreen
        End If
    Else
        TextBox2.Clear()
    End If






End Sub
Aaron Boam
  • 11
  • 2
  • Don't control every key but when the user is finished typing, look here: https://stackoverflow.com/a/8915207/284240 – Tim Schmelter Apr 06 '18 at 08:16
  • You can add `keypress` on textbox and disable all the letters. Check it [here](https://stackoverflow.com/questions/12997290/disabling-alphabetic-letters-and-special-characters-in-visual-basic-net) – Sherwin Obciana Apr 06 '18 at 08:21
  • 1
    I would also suggest handling the `Validating` event of the `TextBox` and checking for valid numeric input there. You can try to prevent invalid input but a rigorous implementation is difficult. The suggestion from @SherwinObciana is fairly naïve, e.g. it doesn't prevent invalid data being pasted in. – jmcilhinney Apr 06 '18 at 08:23
  • [Here](http://www.vbforums.com/showthread.php?618778-Numeric-Text-Box&highlight=)'s my attempt at a rigorous implementation. Some features could be omitted if it's application-specific. – jmcilhinney Apr 06 '18 at 08:24

0 Answers0