How to find and highlight next instance of word in richtextbox in visual basic? - vba

Here is the visual basic windows application form I am currently working on.
https://i.snag.gy/EzoXr3.jpg
How can I write code for the find next button like in this video.
https://www.dropbox.com/s/u93h9jn605uhwsu/CPT341Project2Walkthrough.avi?dl=0
If I can get a syntax to store a index variable outside the private sub of findnext button, I can solve the problem. Because everytime I click the findnext button, I have to find the respective instance of that word in the filetext. Or I can apply some code to find it in the substring of remaining text after its first occurrence.
Below is my code:
Public Class Form1
'Enter your name
'Date
'Class - CPT 341 VB.NET NJIT
Private Sub openBtn_Click(sender As Object, e As EventArgs) Handles openBtn.Click
If OpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
fileText.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog.FileName)
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Bring the form to the inital state for a different search
Dim temp As String = fileText.Text
fileText.Text = temp
outputIndex.ForeColor = Color.Black
'MessageBox to show error for empty search textbox
If inputText.Text = "" Then
MessageBox.Show("Enter Text to Search", "CPT 341 Fall 2018 - Project 2")
Else
'Declare variables
Dim txt As String : Dim x As Integer = 0 : Dim output As String
txt = inputText.Text
If fileText.Text.IndexOf(txt) <> -1 Then
Dim idx As Integer = CStr(fileText.Text.IndexOf(txt))
outputIndex.Text = idx
'Find and highlight the first word searched in the RichTextBox
fileText.Find(txt, x, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
'populate the string with ANSI numbers
output = Asc(txt(0))
For x = 1 To (txt.Length - 1)
output = output & " " & Asc(txt(x))
Next x
outputANSI.Text = output
ElseIf fileText.Text = "" Then
MessageBox.Show("Please open a file to search from", "CPT 341 Fall 2018 - Project 2")
Else
outputIndex.Text = txt & " is not found"
'Bring the form to inital state
fileText.Text = temp
'Change the index textbox text color to red
outputIndex.ForeColor = Color.Red
'Empty the ANSI textbox
outputANSI.Text = ""
End If
End If
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim txt As String = inputText.Text
Dim Index As Integer = fileText.Text.IndexOf(txt) + txt.Length
'Find and highlight the word searched in the RichTextBox other than first occurrence
fileText.Find(txt, Index, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
Index = fileText.Text.IndexOf(txt, Index) + txt.Length + 1
End Sub
Private Sub btnWords_Click(sender As Object, e As EventArgs) Handles btnWords.Click
wordCount.Text = fileText.Text.Split(" ").Length
End Sub
Private Sub btnChars_Click(sender As Object, e As EventArgs) Handles btnChars.Click
charCount.Text = fileText.Text.Length
End Sub
End Class
Or any other suggestion would be helpful.

Related

Exporting CSV from ListView in VB.NET

i am having a bit of issue with exporting my data from a List-view in VB.NET i have included screenshots of what i am seeing basically i want to see only the Values in my csv file when i export it,
as you can see i am seeing what the List-box is showing, those values are coming from the List View Before Export. also i need the export to be in 1 column not rows as shown
any help would be great..
''''
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.StreamWriter
Imports System.Data.DataSet
Public Class Form1
Private Sub startcol_Click(sender As Object, e As EventArgs) Handles startcol.Click
Timer1.Enabled = True
End Sub
Private Sub stopcol_Click(sender As Object, e As EventArgs) Handles stopcol.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Const MIN As Double = 5.0
Const MAX As Double = 400.0
Const DEC_PLACES As Integer = 2
Dim rnd As New Random
Dim list As Integer()
'Generate a random number X where MIN <= X < MAX and then round to DEC_PLACES decimal places.
Dim dbl As Double = Math.Round(rnd.NextDouble() * (MAX - MIN) + MIN, DEC_PLACES)
weight.Text = dbl
Dim newItem As New ListViewItem(weight.Text)
newItem.SubItems.Add(weight.Text)
'newItem.SubItems.Add(TextBox3.Text)
ListBox1.Items.Add(newItem)
ListView1.Items.Add(newItem)
rowcnt.Text = ListView1.Items.Count
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' ExportDatasetToCsv(List)
'WriteToTextFile()
Me.DoSave()
End Sub
Private Sub DoSave()
Dim SFD As New SaveFileDialog()
Try
With SFD
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.OverwritePrompt = True
.ValidateNames = True
.ShowHelp = True
.DefaultExt = "txt"
.Filter = _
"CSV Files (*.csv)|*.csv|" & _
"All files|*.*"
.FilterIndex = 1
If .ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.DoSaveItems(.FileName)
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
' save All values from ListView1
Private Sub DoSaveItems(ByVal fileName As String)
If fileName Is Nothing = False Then
If fileName.Length > 0 Then
Using writer As New System.IO.StreamWriter(fileName)
For Each currentItem As Object In Me.ListView1.Items
writer.Write(currentItem.ToString() & ",")
Next
End Using
End If
End If
End Sub
Public Function ExportListViewToCSV(ByVal filename As String, ByVal lv As ListView) As Boolean
Try
' Open output file
Dim os As New StreamWriter(filename)
' Write Headers
For i As Integer = 0 To lv.Columns.Count - 1
' replace quotes with double quotes if necessary
os.Write("""" & lv.Columns(i).Text.Replace("""", """""") & """,")
Next
os.WriteLine()
' Write records
For i As Integer = 0 To lv.Items.Count - 1
For j As Integer = 0 To lv.Columns.Count - 1
os.Write("""" & lv.Items(i).SubItems(j).Text.Replace("""", """""") + """,")
Next
os.WriteLine()
Next
os.Close()
Catch ex As Exception
' catch any errors
Return False
End Try
Return True
End Function
Public Sub TestExportToCSV()
Dim dlg As New SaveFileDialog
dlg.Filter = "CSV files (*.CSV)|*.csv"
dlg.FilterIndex = 1
dlg.RestoreDirectory = True
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If ExportListViewToCSV(dlg.FileName, ListView1) Then
Process.Start(dlg.FileName)
End If
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TestExportToCSV()
End Sub
End Class
''''
As you haven't shown us your code, we can't tell you how to modify it specifically. In general though, you can treat the ListView somewhat like a 2D array, looping through the rows and the columns to get the data. That means that you could output the data to a CSV like this:
Using writer As New StreamWriter(filePath)
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before all but the first line.
If rowIndex > 0 Then
writer.WriteLine()
End If
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
write.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
That's the old-school way. There are more succinct options, especially with the advent of LINQ:
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))))
EDIT:
If you want to include the column headers then you can modify the above code like so:
Using writer As New StreamWriter(filePath)
For columnIndex = 0 To myListView.Columns.Count - 1
Dim column = myListView.Columns(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(column.Text)
Next
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before each line.
writer.WriteLine()
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))).
Prepend(String.Join(",",
myListView.Columns.
Cast(Of ColumnHeader)().
Select(Function(header) header.Text))))

Highlighting text when searching for it in vb.net

Hi so I've created a search system with a button, textbox and rich text box to search for items displayed in the rich text box (which are imported from a text file) and to highlight them when found. For some reason when I click the search button, it does not highlight the word that is being searched for.
This is the code I used:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim index As Integer = 0
While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text)
rtxtEdit.Find(txtSearch.Text,index ,rtxtEdit.TextLength, RichTextBoxFinds.None)
rtxtEdit.SelectionBackColor = Color.Red
index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1
End While
End Sub
As stated in this post:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim len = searchText.Length
Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight)
While (pos >= 0)
rtb.Select(pos, len)
rtb.SelectionBackColor = Color.Yellow
if pos + len >= rtb.Text.Length Then
Exit While
End If
pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight)
End While
End Sub
I'd write that this way instead:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim searchFor As String = txtSearch.Text.Trim
If searchFor <> "" Then
Dim index As Integer = 0
Dim startAt As Integer = 0
Do
index = rtxtEdit.Find(searchFor, startAt, RichTextBoxFinds.None)
If index <> -1 Then
rtxtEdit.SelectionBackColor = Color.Red
startAt = index + 1
End If
Loop While index <> -1
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim index As Integer = 0
'Clears the existing formatting
Dim t = rtxtEdit.Text
rtxtEdit.Text = t
'Incremented the loop condition by 1 so that text at the beginning gets selected as well.
While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text) + 1
rtxtEdit.Find(txtSearch.Text, index, rtxtEdit.TextLength, RichTextBoxFinds.None)
rtxtEdit.SelectionBackColor = Color.Red
index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1
End While
End Sub

Paste Intercept event failure

I want to intercept a paste event for a FIRST NAME textbox so that if the user pastes "Joe Smith, PhD", they will get "Joe" in the FIRST NAME textbox, and they will see "Smith, PhD" in the LAST NAME textbox. Instead, what I get is "Joe Smith,PhDJoe" in FIRST NAME textbox, and "Smith, PhD" in LAST NAME textbox. I added a messagebox as a breakpoint for me and if I uncomment that line, the msgbox displays and then the sub works perfectly. So, is this a timing issue (Windows 10/VS2015 if that matters)?
There are many posts on how to intercept paste events, and my code below is based on that. What am I doing wrong?
Public Class test
Private Sub TBfname_PASTE(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TBFname.KeyDown
Dim Pasting As String = Clipboard.GetText()
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Dim SplitWhere As Int64 = 0
Dim words = Pasting.Split(" "c)
Dim firstWord = words(0)
If Pasting.Contains(" ") Then
SplitWhere = Pasting.IndexOf(" ")
Dim LN As String = ""
Dim long2 As Int64 = Pasting.Length - SplitWhere - 1
If long2 > 0 Then
LN = Pasting.Substring(SplitWhere + 1, long2)
TBLname.Text = LN
End If
' MsgBox(Pasting & " vs " & TBFname.Text)
TBFname.Text = firstWord
End If
e.Handled = True
End If
End Sub
End Class
One thing you could to is declare firstword as a Form level variable
Private firstWord As String
and then assign it in TBfname_KeyDown
firstWord = words(0)
Then in the KeyUp event re-assign TBfname.Text
Private Sub TBfname_KeyUp(sender As Object, e As KeyEventArgs) Handles TBfname.KeyUp
TBfname.Text = firstWord
End Sub

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

VB.NET Read text file line by line and set every line in textbox with button clicks

hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub
I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub
This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)