locked
How can I compare what is in my text box? RRS feed

  • Question

  • Hi all! It's been a long time and I'm very rusty on my VB.

    I did something like this years ago and now I'm stumped.

    My application flows like this-

    -From my form, I have a text box.

    -I scan a serial number into the text box

    -The application compares the scanned serial number against a base-line serial number

    -Depending on if the serial number is greater, less or equal, a windows messege box is displayed.

    I can get the messeage box to work just fine, it's just the line of code that does all the comparision I'm struggling with.

    - Serial number to baseline is something like SY1420000134 (all the same charater length and always starts with a SY)

    I've been searching for about two hours now and can't find any thread to jog my memory.

    I'm using VB 2010

    Any pointers in the right direction? Many thanks!!!


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Tuesday, May 15, 2012 7:27 PM

Answers

  • Chris,

    See if this helps?

    Option Strict On Option Explicit On ' Public Class Form1 ' Private allSerialNumbers As New List(Of String) ' Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load allSerialNumbers.AddRange(New String() {"apples", _ "oranges", _ "pears", _ "grapes"}) Button1.Enabled = False End Sub ' Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles TextBox1.TextChanged If TextBox1.Text.Trim <> "" Then Button1.Enabled = True Else Button1.Enabled = False End If End Sub ' Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click If allSerialNumbers.Contains(TextBox1.Text.Trim) Then MessageBox.Show("The item is in the list.", "Results", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) Else MessageBox.Show("The item is NOT in the list.", _ "Results", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) End If End Sub ' End Class


    Please call me Frank :)

    • Marked as answer by chris5840 Monday, October 22, 2012 12:15 PM
    Saturday, October 20, 2012 5:35 PM

All replies

  • Hello chris5840,

    Hi all! It's been a long time and I'm very rusty on my VB.

    I did something like this years ago and now I'm stumped.

    My application flows like this-

    -From my form, I have a text box.

    -I scan a serial number into the text box

    -The application compares the scanned serial number against a base-line serial number

    -Depending on if the serial number is greater, less or equal, a windows messege box is displayed.

    I can get the messeage box to work just fine, it's just the line of code that does all the comparision I'm struggling with.

    - Serial number to baseline is something like SY1420000134 (all the same charater length and always starts with a SY)

    I've been searching for about two hours now and can't find any thread to jog my memory.

    I'm using VB 2010

    Any pointers in the right direction? Many thanks!!!


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    where do you get the serial number to compare? and a string of text? so if you have available the Equals () method with which you can compare the value of the TextBox text string and the value of the serial code example

    If TextBox1.Text.Equals ("text string to compare") Then
    'Your messagebox
    end If

    Regards.


    Tuesday, May 15, 2012 7:51 PM
  • In this specific case (because you know you have a fixed string format of two characters followed by ten digits), you can trim off the first two characters and then cast the remaining string into a Long integer and then compare the integer value:

    Public Class Form1
        Private WithEvents SerialNumberTextBox As New TextBox
        Private WithEvents TestButton As New Button With {.AutoSize = True, .Text = "Test"}
        Private WithEvents FlowPanel As New FlowLayoutPanel With {.Dock = DockStyle.Fill}
    
        Private _BaseSerialNumber As String = "SY1420000134"
        Private _BaseNumberValue As Long
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Controls.Add(FlowPanel)
            FlowPanel.Controls.Add(SerialNumberTextBox)
            FlowPanel.Controls.Add(TestButton)
            _BaseNumberValue = CLng(_BaseSerialNumber.Substring(2))
        End Sub
    
        Private Sub TestButton_Click(sender As Object, e As System.EventArgs) Handles TestButton.Click
            Dim number As Long = CLng(SerialNumberTextBox.Text.Substring(2))
            If number = _BaseNumberValue Then
                MessageBox.Show("Same")
            ElseIf number > _BaseNumberValue Then
                MessageBox.Show("Greater")
            Else
                MessageBox.Show("Less")
            End If
        End Sub
    End Class

    Depending on how much you are going to use these serial numbers throughout your program, it might be best to write your own Structure to encapsulate the serial number and its comparison logic:

    Option Strict On
    Option Explicit On
    
    Public Class Form1
        Private WithEvents SerialNumberTextBox As New TextBox
        Private WithEvents TestButton As New Button With {.AutoSize = True, .Text = "Test"}
        Private WithEvents FlowPanel As New FlowLayoutPanel With {.Dock = DockStyle.Fill}
    
        Private _BaseSerialNumber As SerialNumber = "SY1420000134"
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Controls.Add(FlowPanel)
            FlowPanel.Controls.Add(SerialNumberTextBox)
            FlowPanel.Controls.Add(TestButton)
        End Sub
    
        Private Sub TestButton_Click(sender As Object, e As System.EventArgs) Handles TestButton.Click
            Try
                Dim other As SerialNumber = SerialNumberTextBox.Text
                If other = _BaseSerialNumber Then
                    MessageBox.Show("Same")
                ElseIf other > _BaseSerialNumber Then
                    MessageBox.Show("Greater")
                Else
                    MessageBox.Show("Less")
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub
    End Class
    
    Public Structure SerialNumber
        Implements IComparable
        Implements IComparable(Of SerialNumber)
    
        Public Shared ReadOnly Empty As New SerialNumber
    
        Private _Value As String
        Private _Number As Long
    
        Public Sub New(value As String)
            If value Is Nothing OrElse Not value.Length = 12 Then Throw New ArgumentException("Invalid serial number length.")
            value = value.ToUpper
            If Not value.Substring(0, 2) = "SY" Then Throw New ArgumentException("Invalid serial number prefix.")
            If Not Long.TryParse(value.Substring(2), _Number) Then Throw New ArgumentException("Invalid serial number format.")
            _Value = value
        End Sub
    
        Public Overrides Function Equals(obj As Object) As Boolean
            Return CompareTo(obj) = 0
        End Function
    
        Public Overrides Function GetHashCode() As Integer
            Return _Value.GetHashCode
        End Function
    
        Public Overrides Function ToString() As String
            Return _Value
        End Function
    
        Public Function CompareTo(obj As Object) As Integer Implements System.IComparable.CompareTo
            If TypeOf obj Is SerialNumber Then
                Return CompareTo(DirectCast(obj, SerialNumber))
            ElseIf TypeOf obj Is String Then
                Return CompareTo(New SerialNumber(CStr(obj)))
            End If
            Return -1
        End Function
    
        Public Function CompareTo(other As SerialNumber) As Integer Implements System.IComparable(Of SerialNumber).CompareTo
            Return _Number.CompareTo(other._Number)
        End Function
    
        Public Shared Narrowing Operator CType(source As SerialNumber) As String
            Return source._Value
        End Operator
    
        Public Shared Narrowing Operator CType(source As SerialNumber) As Long
            Return source._Number
        End Operator
    
        Public Shared Widening Operator CType(source As String) As SerialNumber
            Return New SerialNumber(source)
        End Operator
    
        Public Shared Operator =(source As SerialNumber, target As SerialNumber) As Boolean
            Return source.CompareTo(target) = 0
        End Operator
    
        Public Shared Operator <>(source As SerialNumber, target As SerialNumber) As Boolean
            Return Not source.CompareTo(target) = 0
        End Operator
    
        Public Shared Operator >(source As SerialNumber, target As SerialNumber) As Boolean
            Return source.CompareTo(target) > 0
        End Operator
    
        Public Shared Operator <(source As SerialNumber, target As SerialNumber) As Boolean
            Return source.CompareTo(target) < 0
        End Operator
    
        Public Shared Operator >=(source As SerialNumber, target As SerialNumber) As Boolean
            Return source.CompareTo(target) >= 0
        End Operator
    
        Public Shared Operator <=(source As SerialNumber, target As SerialNumber) As Boolean
            Return source.CompareTo(target) <= 0
        End Operator
    End Structure


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Marked as answer by chris5840 Tuesday, May 15, 2012 10:45 PM
    • Unmarked as answer by chris5840 Friday, October 19, 2012 12:45 PM
    Tuesday, May 15, 2012 8:55 PM
    Moderator
  • well, my recommendation is to strip the alpha characters off the front, and convert the rest to a number. then its as simple as:

    if A = B 
    ...
    else if A > B
    ...
    else 'A must be less than b'
    ...
    end if

    for stripping and parsing, it should be somthing like:

    dim i as integer = 0
    Integer.TryParse(String.Substring(2), i)


    • Edited by Endotherm Tuesday, May 15, 2012 9:10 PM
    Tuesday, May 15, 2012 9:09 PM
  • Wow. great starting point. Thanks to all that replied. Let me try some things, this is jogging back memories. I don't think is will have to be as complicated as some of the examples, but we'll see.

    GREAT stuff! thanks again and I'll get back with the results!!


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Tuesday, May 15, 2012 10:37 PM
  • 
    
    
    

    The marked as answer was AWESOME!!!!! Easy to follow, easy to tweak for a rough app.

    Thanks so much (I'll make sure to save this snipped so months don't go by and I forget this all over)


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    • Marked as answer by chris5840 Friday, October 19, 2012 12:44 PM
    • Unmarked as answer by chris5840 Friday, October 19, 2012 12:44 PM
    Tuesday, May 15, 2012 10:47 PM
  • Reed-

    Thank you so much for the great pointers. The above app works great.

    Boss gave me another challenge that I'm not sure how to attack. 

    Same logic, but different case:

    I have a very long list of serial numbers. I need to scan these numbers and have windows tell me if the serial number is in the list.

    I'll have to enter these into my project by hand (not a problem). I'm struggling to set up the flow and logic. Same serial number format.

    Any suggestions?


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Friday, October 19, 2012 12:51 PM
  • Reed-

    Thank you so much for the great pointers. The above app works great.

    Boss gave me another challenge that I'm not sure how to attack. 

    Same logic, but different case:

    I have a very long list of serial numbers. I need to scan these numbers and have windows tell me if the serial number is in the list.

    I'll have to enter these into my project by hand (not a problem). I'm struggling to set up the flow and logic. Same serial number format.

    Any suggestions?


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Consider using a List(Of String) and each s/n is added to the list. To then determine if it's in there, just use the .Contains method:

    If serialNumList.Contains(thisSerialNum) Then
        ' It's in there
    End If


    Please call me Frank :)

    Friday, October 19, 2012 3:08 PM
  • ~L~ thanks, Frank. This makes perfect logic. How do I bake it into the above? I'm having issues using the full example aboce and dripping this logic into it so I don't have to start over.

    Thanks for everyone for the help. These boards are worth their weight in gold!! The help is very appreciated.


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Saturday, October 20, 2012 1:05 PM
  • ~L~ thanks, Frank. This makes perfect logic. How do I bake it into the above? I'm having issues using the full example aboce and dripping this logic into it so I don't have to start over.

    Thanks for everyone for the help. These boards are worth their weight in gold!! The help is very appreciated.


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Well it's a bit difficult to say because I'm only seeing a small part of what you're doing, but I'm guessing that you need to first type the numbers in or how are they going to get into the program? If this is an ongoing thing, you might also want to put them into a text file so that you don't have to do it but once.

    Tell me more about it and I'll be happy to comment from there but I don't want to steer you in the wrong direction either.


    Please call me Frank :)

    Saturday, October 20, 2012 2:09 PM
  • ok. Here's how the application works:

    VERY simple windows form with a text box. The form also has a simple submit button. What I need my Team to do is to be able to scan the Serial Number into the text box, press subit and a windows dialog box comes up saying if this serial number is in the list.

    Yes, the serial numbers will be entered into the back end (they are static, they don't change). I have a spreadsheet will all the Serial numbers.

    a sample Serial Number to compare is:

    SY1420000134 Always the same charater legnth and format. Just confused on the VB logic to get this done.


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Saturday, October 20, 2012 3:11 PM
  • ok. Here's how the application works:

    VERY simple windows form with a text box. The form also has a simple submit button. What I need my Team to do is to be able to scan the Serial Number into the text box, press subit and a windows dialog box comes up saying if this serial number is in the list.

    Yes, the serial numbers will be entered into the back end (they are static, they don't change). I have a spreadsheet will all the Serial numbers.

    a sample Serial Number to compare is:

    SY1420000134 Always the same charater legnth and format. Just confused on the VB logic to get this done.


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Chris,

    Last things first - if you have the serial numbers in Excel, you might think about saving it out as a CSV or tab-delimited text file, then read that back in using a TextFieldParser. That would be a fast way to get the initial list that's the topic of discussion here.

    Essentially though, you want to declare a class-level variable for a List(Of String), so it might be something like this:

    Private allSerialNumbers As New List(Of String)

    Now the serial numbers have to be added - either by reading them in using a TextFieldParser like I was just saying, or by whatever means you have in mind.

    With that then, the user is entering the serial number into a TextBox as I understand it? You said they scan it but it ends up being in that TextBox ... or I presume? If I'm wrong then disregard the rest of this! ;-)

    But if I'm right, then in the button's click event, you'd simply test it and respond accordingly:

    If allSerialNumbers.Contains(TextBox1.Text.Trim) Then
        ' Display the message that it's in the list
    Else
        ' Display the message that it's NOT in the list
    End If

    Something like that anyway.


    Please call me Frank :)

    Saturday, October 20, 2012 3:26 PM
  • Let's skip the parser.

    Here's my simple screen shot of my form:

    Simple enough.

    Here's the simple code behind the scenes:

    Public Class Form1
        Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        End Sub
    End Class

    So, million $$ question is how do we tie this all together?

    Again, no need for a parser, the sheet will never change; I just will have to get all the serial numbers into the list by hand only one time.

    And yes, scan would be the same as typing.

    Thoughts?


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Saturday, October 20, 2012 5:22 PM
  • Chris,

    See if this helps?

    Option Strict On Option Explicit On ' Public Class Form1 ' Private allSerialNumbers As New List(Of String) ' Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load allSerialNumbers.AddRange(New String() {"apples", _ "oranges", _ "pears", _ "grapes"}) Button1.Enabled = False End Sub ' Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles TextBox1.TextChanged If TextBox1.Text.Trim <> "" Then Button1.Enabled = True Else Button1.Enabled = False End If End Sub ' Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click If allSerialNumbers.Contains(TextBox1.Text.Trim) Then MessageBox.Show("The item is in the list.", "Results", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) Else MessageBox.Show("The item is NOT in the list.", _ "Results", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) End If End Sub ' End Class


    Please call me Frank :)

    • Marked as answer by chris5840 Monday, October 22, 2012 12:15 PM
    Saturday, October 20, 2012 5:35 PM
  • Outstanding! Instead of parsing the file, I just used the concantanate function and pasted all 2,345 Serial numbers.

    Works PERFECT.

    Thanks everyone SO much for all the help. This works, but more importantly, gives me examples of this logic and taught me.

    Thank you


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    Monday, October 22, 2012 12:15 PM
  • Outstanding! Instead of parsing the file, I just used the concantanate function and pasted all 2,345 Serial numbers.

    Works PERFECT.

    Thanks everyone SO much for all the help. This works, but more importantly, gives me examples of this logic and taught me.

    Thank you


    Dr.Bones- " If my application is too hard for a 5th grader to run, I've made too complicated"

    I'm glad it helped!


    Please call me Frank :)

    Monday, October 22, 2012 12:54 PM