Home > OS >  Check whether value entered in text box falls between values of two other text boxes
Check whether value entered in text box falls between values of two other text boxes

Time:12-01

I have three textboxes. If the value entered in textbox 3 (numeric) is between the values of textbox 1 (numeric) and textbox 2 (numeric), or between the values of textbox 2 and textbox 1 then the result is okay, else it is not okay.

How can this be done with VB.NET?

CodePudding user response:

I haven't written any VB for years, but i think the formula you are looking for can be expressed as:

Return (z >= x And z <= y) Or (z >= y And z <= x)

Where:

  • x is the value from textbox 1
  • y is the value from textbox 2
  • z is the value from textbox 3

Here is my (rusty) attempt at the VB to handle this:

Function IsOk(ByVal firstValue As String, ByVal secondValue As String, ByVal thirdValue As String) As String
    If firstValue.IsInteger() And secondValue.IsInteger() And thirdValue.IsInteger() Then
        Dim x As Integer = Integer.Parse(firstValue)
        Dim y As Integer = Integer.Parse(secondValue)
        Dim z As Integer = Integer.Parse(thirdValue)

        If (z >= x And z <= y) Or (z >= y And z <= x) Then
           Return "OK"
        End If
    End If
    
    Return "Not OK"
End Function

Public Module MyExtensions

    <System.Runtime.CompilerServices.Extension()> _
    Public Function IsInteger(ByVal value As String) As Boolean
        If String.IsNullOrEmpty(value) Then
            Return False
        Else
            Return Integer.TryParse(value, Nothing)
        End If
    End Function

End Module

CodePudding user response:

Always more than one way of doing things. A simplified version of the above code example that returns a boolean value could look like this

Function IsOk(firstValue As String, secondValue As String, thisValue As String) As Boolean
    If IsNumeric(firstValue) And IsNumeric(secondValue) And IsNumeric(thisValue) Then
        Dim x As Integer = firstValue
        Dim y As Integer = secondValue
        Dim z As Integer = thisValue
        If (z >= x And z <= y) Or (z >= y And z <= x) Then
            Return True
        End If
    End If
    Return False
End Function
  • Related