How to replace a word in a textbox with another word - vb.net

I'm writing an article rewriter in VB.NET and I am having a problem in replacing some words with another word.
is there a way i can replace the words directly while the user is typing.
while texting it , i typed "what is love, we always look at it"
and it displayed what is love we frequently look at it
instead of
what is affection we frequently see it
Here is my code:
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
If RichTextBox1.Text.Contains("always") Then
RichTextBox2.Text = RichTextBox1.Text.Replace("always", "frequently")
End If
If RichTextBox1.Text.Contains("love") Then
RichTextBox2.Text = RichTextBox1.Text.Replace("love", "affection")
End If
If RichTextBox1.Text.Contains("look") Then
RichTextBox2.Text = RichTextBox1.Text.Replace("look", "see")
End If 'RichTextBox2.Text = RichTextBox1.Text
End Sub

If I understand the problem correctly, you want to change the text as it's being typed in. You don't want to use the text changed event as it won't occur immediately on typing. Use the keyup event instead.
Private Sub RichTextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyUp
Dim wordToFind As String = "findword"
Dim replaceWord As String = "replaceword"
Richtextbox2.rtf = RichTextBox1.replace(wordToFind, replaceWord)
End If
End Sub

Related

Barcode scanning to a listbox checking for duplicates

Good day!
I want to add some strings from a barcode scanner, captured in a text box, to a list box, and, before adding it, to check if the specific string hasn't been already added. So I have a text box called txtWO which captures what the reader scans and a list box called lstScanBOM to which I add the text box string if the item is not already added. The problem is, that whatever I do, only after the specific string is added twice the checking for duplicate entry starts to work. In other words I scan the same string twice, it added it, and then when I scan the third time only it throws the message with the error saying it is a duplicate. I don't understand why is doing this. The code is below:
Private Sub frmValidareFIP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If txtWO.Focused = False Then
txtWO.Select()
End If
End Sub
Private Sub AddUnique(StringToAdd As String)
If lstScanBom.Items.Contains(StringToAdd) = True Then
MsgBox("Articol duplicat!", vbOKOnly)
Else
'it does not exist, so add it..
lstScanBom.Items.Add(StringToAdd)
End If
End Sub
Private Sub txtWO_KeyDown(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
barcode = txtWO.Text
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
IMO Try listing the data outside of the ListBox. I can't see why it isn't working, maybe we need a third pair of eyes to see it!?
Try adding a list (of string) as a Private within the form, populate this as your user scans, and check the duplicate there..
This is definately not the best solution, but I'm sure it will help!
Private List_Barcodes As List(Of String)
Private Sub frmValidareFIP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
List_Barcodes = New List(Of String)
'You can also populate this list on load, if you have a stored cahce of previous scanned barcodes?
'List_Barcodes.Add("0123456")
'List_Barcodes.Add("4567890")
'...etc
If txtWO.Focused = False Then
txtWO.Select()
End If
End Sub
Private Sub AddUnique(StringToAdd As String)
If List_Barcodes.Contains(StringToAdd) Then
MsgBox("Articol duplicat!", vbOKOnly)
Else
'Place into dynamic list
List_Barcodes.Add(StringToAdd)
'and Place into your listbox
lstScanBom.Items.Add(StringToAdd)
End If
End Sub
Private Sub txtWO_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
barcode = txtWO.Text
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
Your barcode reader is returning <carriage return><line feed> as enter. Your code catches the enter key (carriage return = 13), but leaves the line feed (10) character. So the next time you scan something it will start with a line feed. The two strings in your example are different because the first is "58335001" and the second is "<line feed>58335001". The third one is "<line feed>58335001", which is a duplicate of the second.
One way to fix this is to trim your string.
Private Sub txtWO_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
'Add the .Trim() to remove the leading <line feed> character
barcode = txtWO.Text.Trim()
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
The most simple decision is ONLY to make your textBox control txtWO NOT multiline
And that's enough! Your code will work correctly!

How to pass ListBox selected item into file?

What I have:
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
Dim curItem As String = ChooseProgram.SelectedItem.ToString()
End Sub
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curitem.string")
jhin.Close()
End Sub
I just want to write the string into the file.
How is that possible?
Thx for ur help!
Hannir
UPDATE:
' Ensure an item is selected
If ChooseProgram.SelectedItem Is Not Nothing Then
curItem = ChooseProgram.SelectedItem.ToString()
End If
I get an error here.
"The Is operator does not accept operands of type " integer " . The operands must be reference types, or permit types , NULL values ​​."
Really thx for ur quick help! #Pro Grammer
If you just click Install, and nothing is selected, it ends in an error. So is it possible to say "You need to select an item before" or the Install button is just clickable when selected an item?
For starters you have to move the declaration of the curItem variable out of the SelectedIndexChanged method, to what's called Class level.
As it stands your variable is accessible within your SelectedIndexChanged method only, whereas if you move it to class level it will be accessible by everything within that class (the class in this case is your Form). You then just modify the variable from your SelectedIndexChanged method.
Dim curItem As String = "" 'We'll start with an empty string.
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
curItem = ChooseProgram.SelectedItem.ToString()
End Sub
Now you will be able to access the variable from your button and write it to a file.
The last thing you have to do is to close the StreamWriter that you create so that it will release the lock on the file. The easiest and best way to do so is wrapping it in an Using/End Using block.
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Using jhin As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
End Using
End Sub
EDIT:
To make your button clickable only when an item is selected, first set the button's Enabled property to False via the Property Window in the designer, then use this code in the SelectedIndexChanged event:
Install.Enabled = ChooseProgram.SelectedIndex >= 0
If ChooseProgram.SelectedIndex < 0 Then Return
curItem = ChooseProgram.SelectedItem.ToString()
This is one option:
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim curItem as String = ""
' Ensure an item is selected
If ChooseProgram.SelectedItem IsNot Nothing
curItem = ChooseProgram.SelectedItem.ToString()
End If
' Double checking valid input
If String.IsNullOrWhiteSpace(curItem) Then
' Handle empty input - Display message, etc
' Exit Sub (unless bat handles empty)
End If
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
jhin.Close()
End Sub
Instead of using the ChooseProgram_SelectedIndexChanged event, you can deal with it from here, since you aren't performing any other actions in that method. If you wanted to still use that event, you would assign the string value into a field which could be accessed across the class. Check out Visual Vincent's answer for this example, and also of a Using block, which removes the need to call jhin.Close() manually and also provides a much clearer format

vb.net string lookup in listbox with output as different part of the string

Last Name Finder
what I'm trying to do is create a list of all peoples surnames where the 1st name = #name
although this isn't the exact purpose its easier to try and explain the actual content. i'm aware it may be easier to use a data source, but I want to try and avoid that where possible.
Form_Load
ListBox1.Items.Add("Dean Smith")
ListBox1.Items.Add("John Jones")
ListBox1.Items.Add("David Johnson")
ListBox1.Items.Add("Samantha Thompson")
ListBox1.Items.Add("Claire Frost")
ListBox1.Items.Add("John Brown")
and then some sort of string manipulation to do the following on button_click
if textbox1.text contains "John" then
listbox2.items.add(Jones)
listbox2.items.add(Brown)
else messagebox.show("No matches found")
end if
Thanks for any input.
What I've understood is that you are willing to use your textbox as a filter to the listbox. And this can be achieved by running the query to your db on every TextChanged().
So to give you some guidelines, you can proceed like this;
private Names As List(Of String)
Private Sub Form2_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Names = New List(Of String)
With Names
.Add("Dean Smith")
.Add("John Jones")
.Add("John Brown")
End With
For Each Name As String In Names
ListBox1.Items.Add(Name)
Next
End sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
ListBox1.Items.Clear()
For Each s As String In Names
If s.Substring(0, TextBox1.Text.Length).ToLower = TextBox1.Text.ToLower Then
ListBox1.Items.Add(s)
End If
Next
End Sub
I hope this solution might help you achieve what you wanted. You can also apply direct filter to the List by using a delegate function, which will avoid you from looping again on TextChange().

Validate only newly typed text

I'm making simple application. There is a textbox and a ListBox. When user type something in the textbox, that text add to the ListBox split by space after some validation process. I done it. Here is my code.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox1.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
ListBox1.Items.Add(ValidateText(arrText(i)))
Next i
End Sub
But I want to upgrade it because the validation process take more time. When user type something in the textbox need to do the same process but for only newly typed text. (From the cursor position forward to the end of the text) already validated text doesn’t need to validate again. I think someone can help.
Note: user can be also copy & paste words in the textbox
Thank in advance
I have found a solution thanks to lapheal who member in msdn forum
Private validatedDic As New Dictionary(Of String, String) 'or Dictionary(Of String, Object)?
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox3.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
Dim text As String = String.Empty
If Not validatedDic.TryGetValue(arrText(i), text) Then
text = ValidateText(arrText(i))
validatedDic(arrText(i)) = text
End If
ListBox1.Items.Add(text)
Next i
End Sub

Search ListBox elements in VB.Net

I'm migrating an application from VB6 to VB.Net and I found a change in the behavior of the ListBox and I'm not sure of how to make it equal to VB6.
The problem is this:
In the VB6 app, when the ListBox is focused and I type into it, the list selects the element that matches what I type. e.g. If the list contains a list of countries and I type "ita", "Italy" will be selected in the listbox.
The problem is that with the .Net version of the control if I type "ita" it will select the first element that starts with i, then the first element that starts with "t" and finally the first element that starts with "a".
So, any idea on how to get the original behavior? (I'm thinking in some property that I'm not seeing by some reason or something like that)
I really don't want to write an event handler for this (which btw, wouldn't be trivial).
Thanks a lot!
I shared willw's frustration. This is what I came up with. Add a class called ListBoxTypeAhead to your project and include this code. Then use this class as a control on your form. It traps keyboard input and moves the selected item they way the old VB6 listbox did. You can take out the timer if you wish. It mimics the behavior of keyboard input in Windows explorer.
Public Class ListBoxTypeAhead
Inherits ListBox
Dim Buffer As String
Dim WithEvents Timer1 As New Timer
Private Sub ListBoxTypeAhead_KeyDown(sender As Object, _
e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.A To Keys.Z, Keys.NumPad0 To Keys.NumPad9
e.SuppressKeyPress = True
Buffer &= Chr(e.KeyValue)
Me.SelectedIndex = Me.FindString(Buffer)
Timer1.Start()
Case Else
Timer1.Stop()
Buffer = ""
End Select
End Sub
Private Sub ListBoxTypeAhead_LostFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.LostFocus
Timer1.Stop()
Buffer = ""
End Sub
Public Sub New()
Timer1.Interval = 2000
End Sub
Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
Buffer = ""
End Sub
End Class
As you probably know, this feature is called 'type ahead,' and it's not built into the Winform ListBox (so you're not missing a property).
You can get the type-ahead functionality on the ListView control if you set its View property to List.
Public Function CheckIfExistInCombo(ByVal objCombo As Object, ByVal TextToFind As String) As Boolean
Dim NumOfItems As Object 'The Number Of Items In ComboBox
Dim IndexNum As Integer 'Index
NumOfItems = objCombo.ListCount
For IndexNum = 0 To NumOfItems - 1
If objCombo.List(IndexNum) = TextToFind Then
CheckIfExistInCombo = True
Exit Function
End If
Next IndexNum
CheckIfExistInCombo = False
End Function