0

I have a VB.NET form and the user would select from 40 different values. I want instead of a dropbox with all 40 values to use a textbox that validates if the stirng given by user is one valuo out off those 40 words.

so for example I need the user writes something and validate the string is one of those 40 reserved words like "urgent","post"... maybe these words stored in an array, and then compared what user wrote against that?

TextBox1.Text.Contains("urgent")
TextBox1.Text.Contains("post")
TextBox1.Text.Contains("standard")
TextBox1.Text.Contains("stay")

Maybe a method

Public Function Contains(ByVal value As String) As Boolean   
    Return (   TextBox1.Text(value, ...) >= 0)
End Function 

What would be the best way to do this?

2 Answers 2

1

You can create a List(of String) of your Reserved Words use the Contains method to check if what was typed was one of them using your Contains function something like this. I am not sure how large the Text you are going to be parsing so I am splitting it into individual words.

Public Class Form1
    Dim reservedWords As List(Of String) = New List(Of String)({"urgent", "post", "standard", "stay"})

    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
        Dim text As String = CType(sender, TextBox).Text
        If ContainsReservedWord(text) Then Beep()
    End Sub

    Public Function ContainsReservedWord(value As String) As Boolean
        Dim x As Integer
        Dim stringSplit As String() = value.Split
        If stringSplit.Count > 0 Then
            For x = 0 To stringSplit.Count - 1
                If reservedWords.Contains(LCase(stringSplit(x))) Then  Return True
            Next
        End If
        Return False
    End Function

End Class
2
  • The beep() sound is to indicate things went right, is that correct?
    – edgarmtze
    Oct 17, 2012 at 3:00
  • @cMinor Yes, it was a quick and dirty test to see if it worked. I am also converting your text to lower case, so that all cases of your text will be checked as long as you build the list with lower case strings
    – Mark Hall
    Oct 17, 2012 at 3:03
0

Use the below code to validate the string that belongs to reserved words or not.

var lstReservedWords = new List<string> {"urgent", "post", "standard", "stay", .......};
bool isReservedWord = lstReservedWords.Any(r => String.Compare(r, TextBox1.Text, true) == 0);

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.