Table of Contents
Find and Replace a String in TextBox, ListBox and ComboBox
Here you can search a text from a listbox, combobox or a multi line textbox.
Finding a particular string from a paragraph or from a list box is a common question arises in Visual Basic examination.
Search a string from paragraph of text
Here multiline textbox is used to type text and an input box accept search string. If the given string is found on the paragraph, then message box shows the result of search whether it is ‘Found’ or ‘Not found’.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = InputBox(“Enter the keyword to search”)
If TextBox1.Text.Contains(str) Then
MessageBox.Show(“Found”)
Else
MessageBox.Show(“Not found”)
End If
End Sub
Search and replace a string from paragraph of text
Here an input box accept a string for search and if the given string is found on the paragraph, then another input box ask the string to replace first one.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
Dim replceStr As String
str = InputBox(“Enter the keyword to search for replace”)
If TextBox1.Text.Contains(str) Then
replceStr = InputBox(“Enter the word for replace”)
TextBox1.Text = TextBox1.Text.Replace(str, replceStr)
Else
MessageBox.Show(“Sorry, given string is not found”)
End If
End Sub
Searching an Item on List Box:
Here input box accept search text and a FOR loop continuously check every item on the listbox. The limit of the list box is the item count of the list box item. If an item matched with given search text, then a checker get a value 1 else the value will be 0. After the loop, program check the value of the checker variable. If it is 1, which means one of item matched.
Private Sub Button11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button11.Click
Dim str As String
Dim i As Integer
Dim position as Integer
Dim checker As Integer = 0
str = InputBox(“Enter the keyword to search”)
For i = 0 To ListBox1.Items.Count – 1
If ListBox1.Items(i) = str Then
checker = 1
position = i + 1
Exit For
End If
Next
If checker = 1 Then
MessageBox.Show(“The string ” + str + ” is found at positoin: ” + position.ToString)
checker = 0
Else
MessageBox.Show(“Not Found”)
End If
End Sub
Position denotes the position of the search text on the list box.
You can use almost these same codes for searching an item from ComboBox. Note that all above codes are not optimized and not completely error free.
Be First to Comment