Text Search And Replacement - vb.net

I am working with visual basic and i'm creating a function which performs a search for each word that is entered into a richtextbox. As a word is being entered into RichTextBox2 a search Is performed in RichTextBox1 and the text is highlighted .
RichTextBox1 and RiochTextBox2 are read only , RichTextBox2 is able to be written in via code while RichTextBox1 has only default text (A directory of words). There is also RichTextBox3 which holds a copy of RichTextBox2's text
RichTextBox3.Text = RichTextBox2.Text
this is the code for the function .
public class textsearch
Private intPosition As Integer
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
generatekanji()
' Static intStart As Integer
'used to select compare method
Dim intStart As Integer
Dim objType As Object
Dim lastWord As String = RichTextBox2.Text.Split(" ").Last
objType = CompareMethod.Text
'set starting position to 1
intPosition = 1
'use the InStr function to look up a staring position of a search string in a given text box using objType (case-insensitive or case-sensitive)
intStart = InStr(intPosition, RichTextBox1.Text, lastWord, objType) ' what it searches
If intStart > 0 Then
'set starting select position on a textbox and select the search string
RichTextBox1.SelectionStart = intStart - 1
RichTextBox1.SelectionLength = lastWord.Length 'highlights the searched word
RichTextBox1.Select()
End If
End Sub
End Class
This is a very useful function but the main issues are
(1) because RichTextBox1 is read only , you gear the "ding" sound each time a search is being performed and it gets very annoying.
(2) I am unable to find a way to select the character whenever a word is found , or how to replace the word in RichTextBox3 with the character next to the searched word.
Could someone help with this problem .

When I use this code the search word is highlighted with no dinging, in a readonly richtextbox:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim SearchWord As String = RichTextBox2.text
Dim SelStart As Integer = InStr(RichTextBox1.Text, SearchWord, CompareMethod.Text)
If SelStart > 0 Then
RichTextBox1.Select(SelStart - 1, SearchWord.Length)
RichTextBox1.Focus()
For Each line In RichTextBox1.Lines
If line.Contains(SearchWord) Then
RichTextBox3.Text = line.Split()(0)
End If
Next
End If
End Sub
I'm wondering if the dinging is coming from the generatekanji() routine.

Related

vb.net save textbox values for later use

I use a textbox in my form to search for words in pdf files. I want to save these search words somewhere for later use. So when the user types a letter in the textbox there will be a pulldown with previous searched words. Something like windows does in Explorer.
Does anyone have an example or is someone familiar with this?
You can store and retrieve a list of search words in an application settings entry of type StringCollection as the data source of the TextBox.AutoCompleteCustomSource property.
Add new entry
Select YourAppName Properties from the Project menu.
Select the Settings tab.
Add new entry in the Name column, say: SearchWords.
From the Type column, select System.Collections.Specialized.StringCollection.
Close the dialog and save.
Retrieve the search words
In the Form's constructor or Load event, say you have a search TextBox named txtSearch:
' +
Imports System.Linq
Imports System.Collections.Specialized
Private Sub YourForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.SearchWords Is Nothing Then
My.Settings.SearchWords = New StringCollection
End If
Dim acc As New AutoCompleteStringCollection
acc.AddRange(My.Settings.SearchWords.Cast(Of String).ToArray())
txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
txtSearch.AutoCompleteCustomSource = acc
End Sub
Update the collection
You need to add the new words whenever you perform a search:
' When you click a search button...
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
AddSearchWord()
End Sub
' If you call the search routine when you press the Enter key...
Private Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
If e.KeyCode = Keys.Enter Then
AddSearchWord()
End If
End Sub
' Update the collection...
Private Sub AddSearchWord()
If txtSearch.Text.Trim.Length = 0 Then Return
If Not txtSearch.AutoCompleteCustomSource.Contains(txtSearch.Text) Then
If txtSearch.AutoCompleteCustomSource.Count > 10 Then
txtSearch.AutoCompleteCustomSource.RemoveAt(
txtSearch.AutoCompleteCustomSource.Count - 1)
End If
txtSearch.AutoCompleteCustomSource.Insert(0, txtSearch.Text)
End If
End Sub
Save the collection
Update the SearchWord string collection when you close the Form:
Private Sub YourForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
My.Settings.SearchWords = New StringCollection
My.Settings.SearchWords.AddRange(txtSearch.AutoCompleteCustomSource.Cast(Of String).ToArray)
My.Settings.Save()
End Sub
Demo
I found some code Saving text box values to a file to load again that I changed to my needs. It saves the content of my ComboBox1 to a textfile when I click my Submit button. When I load the form the textfile is read and loaded into the ComboBox1 as previous used searches.
'now save the search word to our textfile
PresetName = TextBoxFreeText.Text
If PresetName <> "" Then
TextBoxFreeText.Items.Add(PresetName)
Call SaveData(PresetName)
End If
The code to load the saved values:
Private Sub ReadData()
If My.Computer.FileSystem.FileExists(FilePath) = True Then
myReader = New StreamReader(FilePath)
Dim myText = myReader.ReadLine
While myText IsNot Nothing
listPreset.Add(myText)
myText = myReader.ReadLine
End While
myReader.Close()
'Add Preset Names to ComboBox
If listPreset.Count > 0 Then
Dim PresetName As String
Dim index As Integer
For i = 0 To listPreset.Count - 1
index = listPreset.Item(i).IndexOf(",")
PresetName = Mid(listPreset.Item(i), 1, index)
TextBoxFreeText.Items.Add(PresetName)
Next
End If
End If
End Sub
The code to save the content of ComboBox1
Private Sub SaveData(ByVal PresetName As String)
Dim FileString As String = PresetName & ","
'Build File String
FileString &= TextBoxFreeText.Text & ","
listPreset.Add(FileString)
myWriter = New StreamWriter(FilePath)
For i = 0 To listPreset.Count - 1
myWriter.WriteLine(listPreset.Item(i))
Next
myWriter.Close()
End Sub
There are still two things I want to change. I will ask in a new question.
prevent duplicate search string to be entered in the textfile.
set a maximum to the search string loaded in ComboBox1 (maybe 10 words)

How do I add the results to the list?

I am trying to make a program that includes all the presidents and lets you search any letter or name to show the results of presidents associated with that letter or name. However, I am having trouble with actually adding them to the list. This is a class project, so the code is designed to meet requirements for that. Specifically, the part where it says
'Show the match
addPresidentsToList(presidents(idxReturned), idxReturned)
This is saying it isn't declared, but I'm not sure how to go about it.
Any tips or advice would be appreciated, thanks!
Public Class frmLab32
Const IDX_START As Integer = 0
Const IDX_END As Integer = 1
Const IDX_NAME As Integer = 2
Dim presidents() As String
Dim headerRowNeeded As Boolean
Private Sub frmLab32_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Populate array from file
presidents = IO.File.ReadAllLines("USPresWithDates.txt")
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim idxReturned As Integer = -1
Dim idxStart As Integer = 0
'remove names
lstResults.Items.Clear()
'Header row?
headerRowNeeded = True
'Search for matches
Do
idxReturned = Array.FindIndex(presidents,
idxStart,
Function(el) el.Split(","c)(IDX_NAME).ToLower.Contains(txtSearch.Text.ToLower))
'Match Found?
If idxReturned > -1 Then
'Show the match
addPresidentsToList(presidents(idxReturned), idxReturned)
'Prepare for next search
idxStart = idxReturned + 1
End If
Loop Until idxReturned = -1
'Any names found?
If lstResults.Items.Count = 0 Then
'Update counter
lblCount.Text = "0"
'Tell User
MessageBox.Show(text:="No match found",
caption:="Search Results",
buttons:=MessageBoxButtons.OK,
icon:=MessageBoxIcon.Information)
End If
End Sub
End Class
My text file looks like this.
Washington, George
Adams, John
Jefferson, Thomas
Madison, James
Monroe, James
etc.
I use default names for controls in my text program but it is much better to use descriptive name like you did.
In the Form.Load I set the MaxLength property of the TextBox to 1. This will only allow a single character to be typed in the TextBox. You could set this property in the form designer and skip this line of code. Next fill the presidents array exactly as you did.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox5.MaxLength = 1
presidents = IO.File.ReadAllLines("C:\Users\maryo\Desktop\Presidents.txt")
End Sub
Now for the search button. We need to validate the user input. A user could enter a number or punctuation character. Char https://learn.microsoft.com/en-us/dotnet/api/system.char?view=netcore-3.1#:~:text=Remarks-,.,bit%20numeric%20(ordinal)%20value. is a .net structure representing a character. It provides some interesting methods that can be helpful from time to time. Char.IsLetter() tells us (true or false) if a character is a letter. Just what we want to know. The only problem is a String is not a Char and .Text property of a TextBox is a String. Since we limited the entry to a single character we can convert this String to a Char with CChar(). If it is a letter we make the assignment to SelectedLetter otherwise we correct the user and exit the method.
Instead of all the index stuff we can use a For Each loop. It checks each element in presidents. String has a method called StartsWith. We can check each string in presidents to see if it .StartsWith the SelectedLetter. If it does, add it to the ListBox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
'Validate user input
Dim SelectedLetter As String = ""
If Char.IsLetter(CChar(TextBox5.Text)) Then
SelectedLetter = TextBox5.Text.ToUpper
Else
MessageBox.Show("Please enter a letter A - Z.", "Enter Letter")
Exit Sub
End If
For Each pres In presidents
If pres.StartsWith(SelectedLetter) Then
ListBox1.Items.Add(pres)
End If
Next
If ListBox1.Items.Count = 0 Then
'Tell User
MessageBox.Show("No match found", "Search Results")
End If
End Sub

Autocomplete for single word in datagridview

I would need to implement a autocomplete feature in a datagridview cell. I would need it to work on a word by word basis, like it is in the SMS app on android. After I type a whitespace it should start looking for the word I am typing and propose it based on the other words i have already used inside the same Datagridview.
Its more a word suggestion, that if i hit tab autocompletes that word for me.
Is this possible? I know how to do it based on the entire cell, but have no clue on how to do it based on the single word. (like Google)
Thanks
EDIT:
So far I have this. The concept is working, but I need to update the list each time that a key is pressed. Any help on this?
Private Sub DataGridView2_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
wrdlst.Add("arabia")
wrdlst.Add("burundi")
wrdlst.Add("closed")
wrdlst.Add("afganistan")
wrdlst.Add("door")
wrdlst.Add("banana")
wrdlst.Add("apple")
Dim basestring As String = Nothing
basestring = CStr(DataGridView2.CurrentCell.Value)
If Not IsNothing(basestring) Then
Dim lastword As String
Dim lastspaceindex As Integer = basestring.LastIndexOf(" ") + 1 '''+1 to get index after whitespace and compensate for -1 result
lastword = basestring.Substring(lastspaceindex)
Dim ItemCode As TextBox = TryCast(e.Control, TextBox)
If ItemCode IsNot Nothing Then
ItemCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend
'ItemCode.AutoCompleteCustomSource = wrdlst
For Each element As String In wrdlst
If element.StartsWith(lastword) Then
ItemCode.AutoCompleteCustomSource.Add(basestring.Substring(0, lastspaceindex) & element)
End If
Next
ItemCode.AutoCompleteSource = AutoCompleteSource.CustomSource
End If
End If
End Sub
Private Sub DataGridView2_KeyUp(sender As Object, e As KeyEventArgs) Handles DataGridView2.KeyUp
??????????????????????????????????????????
End Sub

label loop for next visual basic

Currently my code looks like this:
Private Sub btnMotivate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMotivate.Click
Dim intNumber As Integer
Dim strStudy As String = "Study!"
intNumber = InputBox("How many times do you want to be motivated? Please use numbers!")
If intNumber < 1 Then
MessageBox.Show("Please use a number from 1 - 10!")
End If
If intNumber > 10 Then
MessageBox.Show("Please use a number from 1 - 10!")
End If
> For intCounter = 1 To intNumber Step 1
lblMotivation.Text = strStudy
> Next
End Sub
As you can see, I have added a variable and the loop runs fine, but I need help phrasing the code so whatever number the user inputs, is the number of lines of "Study!" displayed. I have tried using the string but also using the label with Environment.NewLine hoping it would add a new line every time the loop runs
You are setting the label text to strStudy each time. This doesn't add to what's there already, it just replaces it.
You need to add strStudy to the text that already exists, something like this:
' start with an empty string
lblMotivation.Text = ""
For intCounter = 1 To intNumber Step 1
' append the study string and a newline
lblMotivation.Text = lblMotivation.Text & strStudy & Environment.NewLine
Next
Instead of using a TextBox, use a ListBox to display the word Study! n -times. It is also good practice not to instruct the user to do something, but prevent it in code. Also note how intNumber has been changed to *inp*Number As Object
Private Sub btnMotivate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMotivate.Click
Dim inpNumber As Object
Dim strStudy As String = "Study!"
Dim intCounter As Integer
inpNumber = InputBox("How many times do you want to be motivated?")
If Not IsNumeric(inpNumber) Then
MessageBox.Show("Please enter a number!")
ElseIf inpNumber < 1 OrElse inpNumber > 10 Then
MessageBox.Show("Please enter a number from 1 - 10!")
Else
ListBox1.Items.Clear()
For intCounter = 1 To inpNumber Step 1
ListBox1.Items.Add(strStudy)
Next
End If
End Sub

Remove Whitespace from Line Item in ListBox (VB)

I'm trying to remove all spaces in on all Line Items in a ListBox. I would have assumed I could just throw in a normalize whitespace function but that doesn't appear to be the case. Long story short, I'm trying to write a program that counts the number of XML Fields from a file. I'd like to display all the fields but kill all the spacing in front of it (since it's formatted as XML).
'Imports System.IO
Public Class Form1
Dim theFile As StreamReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTheFile.Click
'Load the File
theFile = New StreamReader("C:\Users\Marc Wilson\Documents\XML\sampledata.xml")
While (theFile.Peek > -1)
ListBox1.Items.Add(theFile.ReadLine)
End While
theFile.Close()
'Only get the fields
Dim numberOfLines As Integer = ListBox1.Items.Count
For i = 0 To numberOfLines - 1
Dim theLineItem As String = ListBox1.Items.Item(i).ToString
If theLineItem.Contains("<my:") And theLineItem.Contains("/>") Then
ListBox2.Items.Add(theLineItem)
End If
Next
'Count items
lblCount.Text = ListBox2.Items.Count.ToString
End Sub
End Class
this will remove leading and trailing spaces
theFile.ReadLine.trim