Code always search the last record not the number I inputed - vb.net

Why my code always search the last record not the one I searched, like this 8850338005909.
Here is code Sample Data in Textfile:
8501045891528,2271,"ADAMS CNDY HALLS
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338001604,2271,"ADAMS CNDY HALLS
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338005909,2271,"ADAMS CNDY HALLS
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338002519,2312,"CLRTS CNDY COOL MINT
40S/60",27.75,60.00,7049,1,100,101,465 8850338001000,2313,"ADAMS GUM
CLRETSTWIN PK14GX2/1",66.50,1.00,4822,1,100,101,470
4804880224138,2315,"BGUIO OIL CKNG
16KG/1",978.00,1.00,6135,1,192,193,639
And my code:
Private Sub Data2()
Dim text As String = IO.File.ReadAllText("C:\ITEMRTV.txt")
Dim index As Integer = text.IndexOf(TextBox1.Text)
Dim Values() As String = Split(text, ",")
If index >= 0 Then
' String is in file, starting at character "index"
Label1.Text = Values(0) ' now contains first column value,
Label2.Text = Values(1) ' contains second column, etc.
Label3.Text = Values(2)
Label4.Text = Values(3)
Label5.Text = Values(4)
Label6.Text = Values(5)
End If
End Sub

Try this:
Dim text As String = IO.File.ReadAllText("C:\ITEMRTV.txt")
Dim Values() As String = text.Split(New String() {",", Environment.NewLine}, StringSplitOptions.None)
Dim index As Integer = Array.IndexOf(Values, TextBox1.Text)
If index >= 0 Then
Label1.Text = Values(index)
Label2.Text = Values(index + 1)
Label3.Text = Values(index + 2)
Label4.Text = Values(index + 3)
Label5.Text = Values(index + 4)
Label6.Text = Values(index + 5)
End If
But you should divide into lines and columns:
Dim text() As String = IO.File.ReadAllLines("C:\ITEMRTV.txt")
Dim s() As String
For Each line As String In text
s = line.Split(","c)
If s(0).Equals(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) _
AndAlso s.Length > 5 Then
Label1.Text = s(0)
Label2.Text = s(1)
Label3.Text = s(2)
Label4.Text = s(3)
Label5.Text = s(4)
Label6.Text = s(5)
Exit For
End If
Next
You could even create your own structure to hold the data, what would be the better option. For example, declarin a Dictionary(Of Integer, List(Of String)) for each file, because the first field looks like a ID, or declaring your own class to hold each field appropiately.

Related

Repeat character in Two or More Textboxes VB Net

I want to compare the Textbox1 with TextBox2, or Textbox line 1 of the text box to the 2nd line, to show me the existing Character in another textbox, or show me how many characters are repeated. iI really like learning, so I would be helpful because I want to learn...
TextBox1.Text = 1,4,7,11,13,16,19,20,28,31,44,37,51,61,62,63,64,69,71,79,80
TextBox2.Text = 1,5,7,10,13,16,26,20,28,31,44,37,51,72,73,74,69,71,79,80
TextBox3.Text = Character Repeated: 1,7,13,16,20,28,31,44,37,51,69,71,79,80
TextBox4.Text = Number of Character Repeated = 14
TextBox5.Text = Number of Character which has not been repeated: 4,11,19,61,62,63,64 etc, you got to idea
TextBox6.Text = Number of Character isn't Repeated: 7
here are some codes: but I do not know how to apply them correctly.
Code 1: Show repetable character:
' Split string based on space
TextBox1.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox2.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox4.Text = System.IO.File.ReadAllText(Mydpi.Text)
For i As Integer = 0 To TextBox2.Lines.Count - 1
Dim textsrtring As String = TextBox4.Lines(i)
Dim words As String() = textsrtring.Split(New Char() {","c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As Integer
For Each word In words
TxtbValBeforeCompar.Text = TextBox1.Lines(i)
CompareNumbers()
If TextBox1.Lines(i).Contains(word) Then
found = True
Dim tempTextBox As TextBox = CType(Me.Controls("Checkertxt" & i.ToString), TextBox)
On Error Resume Next
If TextBox2.Lines(i).Contains(word) Then
If tempTextBox.Text.Contains(word) Then
Else
tempTextBox.Text = tempTextBox.Text + " " + TxtbValAfterCompar.Text()
End If
Else
End If
End If
Next
Next
Private Sub CompareNumbers()
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(N1Check.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtbValBeforeCompar.Text)
'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()
'This is purely for testing to see if it worked you can.
Dim sb As StringBuilder = New StringBuilder()
For Each foundNum As Integer In commonNumbers
sb.Append(foundNum.ToString()).Append(" ")
TxtbValAfterCompar.Text = (sb.ToString())
Next
End Sub
Private Function GetNumbersFromTextLine(ByVal sTextLine As String) As List(Of Integer)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(" ")
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
TxtbValAfterCompar.Text = iNum
If Not numberList.Contains(iNum) Then
TxtbValAfterCompar.Text = ("")
numberList.Add(iNum)
End If
Else
End If
Next
Return numberList
End Function
Code 2: Remove Duplicate Chars (Character)
Module Module1
Function RemoveDuplicateChars(ByVal value As String) As String
' This table stores characters we have encountered.
Dim table(value.Length) As Char
Dim tableLength As Integer = 0
' This is our result.
Dim result(value.Length) As Char
Dim resultLength As Integer = 0
For i As Integer = 0 To value.Length - 1
Dim current As Char = value(i)
Dim exists As Boolean = False
' Loop over all characters in the table of encountered chars.
For y As Integer = 0 To tableLength - 1
' See if we have already encountered this character.
If current = table(y) Then
' End the loop.
exists = True
y = tableLength
End If
Next
' If we have not encountered the character, add it.
If exists = False Then
' Add character to the table of encountered characters.
table(tableLength) = current
tableLength += 1
' Add character to our result string.
result(resultLength) = current
resultLength += 1
End If
Next
' Return the unique character string.
Return New String(result, 0, resultLength)
End Function
Sub Main()
' Test the method we wrote.
Dim test As String = "having a good day"
Dim result As String = RemoveDuplicateChars(test)
Console.WriteLine(result)
test = "areopagitica"
result = RemoveDuplicateChars(test)
Console.WriteLine(result)
End Sub
End Module
You could make use of some LINQ such as Intersect and Union.
Assuming your TextBox1 and TextBox2 contains the text you have provided.
Here's a simple method to find repeated and non repeated characters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
For Each str As String In intersectionList
TextBox3.Text = TextBox3.Text & str & ","
Next
TextBox4.Text = intersectionList.Count()
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
For each str As String In notRepeatedCharacter
TextBox5.Text = TextBox5.Text & str & ","
Next
TextBox6.Text = notRepeatedCharacter.Count()
End Sub
The output is something like that:
This consider both of the textboxes not repeated character.
If you just want to find the not repeated characters from first list to the second, this should do it:
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
For Each str As String In firstBoxList
TextBox7.Text = TextBox7.Text & str & ","
Next
TextBox8.Text = firstBoxList.Count
And this is the output:
Here's the full code using String.Join to make the lists look smoother in the text boxes:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First we grab all the numbers written inside the textboxes (I am not verifying anything)
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
'Second we intersect the two lists and show them
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
TextBox3.Text = String.Join(",", intersectionList)
TextBox4.Text = intersectionList.Count()
'We're checking the distintc character from both lists
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
TextBox5.Text = String.Join(",", notRepeatedCharacter)
TextBox6.Text = notRepeatedCharacter.Count()
'we're checkng the distinct character inside first list that doesn't show in second list
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
TextBox7.Text = String.Join(",", firstBoxList)
TextBox8.Text = firstBoxList.Count
End Sub

How to I add the total of a particular column in a list view and add it into a text box?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
If txtCode.Text = "" Or txtName.Text = "" Or txtUnit.Text = "" Or txtPrice.Text = "" Then
MsgBox("Please fill in all fields")
Else
Dim str(3) As String
Dim itm As ListViewItem
str(0) = LSet(txtName.Text, 8)
str(1) = LSet(txtCode.Text, 3)
str(2) = LSet(txtUnit.Text, 6)
str(3) = LSet(txtPrice.Text, 20)
itm = New ListViewItem(str)
ListView1.Items.Add(itm)
lblTotalItems.Text = ListView1.Items.Count
txtCode.Text = ""
txtName.Text = ""
txtUnit.Text = ""
txtPrice.Text = ""
End If
End Sub
I currently have this code for my list view, with more code in my global variables, I'm wanting to add up one column and place them in the Total text box, I know you have to loop through it and add them but i'm not sure how.
Here is the image for the form
Here is an example of the type of loop you could use.
Const col As Integer = 3 'this adds the price column
Dim total As Integer = 0
Dim lvsi As ListViewSubItem
For i As Integer = 0 To ListView1.Items.Count - 1
lvsi = ListView1.Items(i).SubItems(col)
total += Integer.Parse(lvsi.Text)
Next
A lot simple than a ListView use a DataGridView
Just initialize it on Form.Load() with:
DataGridView1.Columns.Add("Name", "Name")
DataGridView1.Columns.Add("Code", "Code")
DataGridView1.Columns.Add("Unit", "Unit")
DataGridView1.Columns.Add("Price", "Price")
DataGridView1.AllowUserToAddRows = False
Then on Add button:
If txtCode.Text = "" Or txtName.Text = "" Or txtUnit.Text = "" Or txtPrice.Text = "" Then
MsgBox("Please fill in all fields")
Else
DataGridView1.Rows.Add(txtName.Text, txtCode.Text, txtUnit.Value, Decimal.Parse(txtPrice.Text, System.Globalization.CultureInfo.InvariantCulture) * txtUnit.Value)
DataGridView1.Refresh()
End If
Here I did the Price column = the Unit times the price you entered.
I also handled decimals partly but you would need to check that price is 2.00 and not 2
Then for total button:
Dim MyTotal As Decimal = 0.00
'For each row in the gridd
For Each row As DataGridViewRow In DataGridView1.Rows
'invcrement total with column 3 equal to the price (index start = 0)
MyTotal = MyTotal + Decimal.Parse(row.Cells(3).Value, System.Globalization.CultureInfo.InvariantCulture)
Next
txtTotal.Text = MyTotal
I'll let you figure out the rest

How to generate all combinations of partitioning a string in VB.Net

Given a string, how do you generate all partitions of it (shown as smaller strings separated by commas)?
Also, what is the total number of partitions for a string of length n?
The following will give the result, but is not good on long strings.
String: CODE
C,O,D,E
C,O,DE
C,OD,E
C,ODE
CO,D,E
CO,DE
COD,E
String: PEACE
P,E,A,C,E
P,E,A,CE
P,E,AC,E
P,E,ACE
P,EA,C,E
P,EA,CE
P,EAC,E
PE,A,C,E
PE,A,CE
PE,AC,E
PE,ACE
PEA,C,E
PEA,CE
Sub getAllComb()
oriStr = TextBox1.Text
Dim tmp = ""
Dim k = 0
For i = 0 To oriStr.Length
For j = 1 To 3
'tmp = Mid(oriStr, i, j)
Try
tmp1(k) = oriStr.Substring(i, j)
k = k + 1
'tmp = oriStr.Substring(i, j)
'Debug.Print(tmp)
Catch ex As Exception
'Debug.Print("Error>>>>" + ex.Message)
Exit For
End Try
Next
Next
tmp = ""
For i = 0 To k
Debug.Print(i.ToString + "<i " + tmp1(i))
tmp = tmp & tmp1(i) & vbCrLf
Next
'MessageBox.Show(tmp)
Dim tmpAll1 = ""
tmpAll1 = addFunclen4(k)
MessageBox.Show(tmpAll1)
Debug.Print(tmpAll1)
TextBox1.Text = oriStr & vbCrLf & vbCrLf & tmpAll1
End Sub
Function addFunclen4(k As Integer) As String
Dim retVal = ""
Dim tmp = ""
Dim tmpAll = ""
Dim tmpStr = ""
Dim tmpAll1 = ""
For i = 0 To k
For i1 = 0 To k
For i2 = 0 To k
For i3 = 0 To k
For i4 = 0 To k
tmp = Form1.tmp1(i) + Form1.tmp1(i1) + Form1.tmp1(i2) + Form1.tmp1(i3) + Form1.tmp1(i4)
If Form1.tmp1(i) <> "" Then
If tmp = Form1.oriStr Then
tmpStr = Form1.tmp1(i) + "," + Form1.tmp1(i1) + "," + Form1.tmp1(i2) + "," + Form1.tmp1(i3) + "," + Form1.tmp1(i4)
Do While tmpStr.Contains(",,") = True
tmpStr = Replace(tmpStr, ",,", ",")
Loop
If Mid(tmpStr, tmpStr.Length, 1) = "," Then
tmpStr = Mid(tmpStr, 1, tmpStr.Length - 1)
End If
If tmpAll1.Contains(tmpStr) = False Then
tmpAll1 = tmpAll1 + tmpStr + vbCrLf
End If
End If
End If
Next
Next
Next
Next
Next
retVal = tmpAll1
Return retVal
End Function
I reckon [2^(n-1) - 1] in total:
(n-1) positions to put a comma, 2 "states" (comma or not comma), -1 for the trivial case with no commas.
A simpler algorithm would be to iterate through the number of cases and use the binary representation to determine whether to put a comma in each position.
For example (simple form with TextBox, Button and ListBox):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Return
End If
For i = 1 To Math.Pow(2, s.Length - 1) - 1
Dim result As String = s(0)
For j = 1 To s.Length - 1
result = result & CommaOrNot(i, j) & s(j)
Next
ListBox1.Items.Add(result)
Next
End Sub
Private Function CommaOrNot(i As Integer, j As Integer) As String
If (i And Math.Pow(2, j - 1)) = Math.Pow(2, j - 1) Then
Return ","
Else
Return ""
End If
End Function
I really liked Fruitbat's approach. Here's an alternate version using a slightly different mechanism for the representation of the binary number and how to determine if the comma should be included or not:
Public Class Form1
Private combinations As List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Exit Sub
End If
Button1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...")
BackgroundWorker1.RunWorkerAsync(s)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim s As String = e.Argument
Dim combinations As New List(Of String)
Dim binary() As Char
Dim values() As Char = s.ToCharArray
Dim max As Integer = Convert.ToInt32(New String("1", s.Length - 1), 2)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To max
sb.Clear()
binary = Convert.ToString(i, 2).PadLeft(values.Length, "0").ToCharArray
For j As Integer = 0 To values.Length - 1
sb.Append(If(binary(j) = "0", "", ","))
sb.Append(values(j))
Next
combinations.Add(sb.ToString)
Next
e.Result = combinations
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
combinations = e.Result
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...Done!")
ListBox1.Items.Add("Adding Results...one moment please!")
Application.DoEvents()
ListBox1.DataSource = Nothing
ListBox1.DataSource = combinations
Button1.Enabled = True
MessageBox.Show("Done!")
End Sub
End Class

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If

Highlight text in a richtextbox in windows forms

How to make when i type in a RichTextBox a certain word it gets highlited?
how do i find words in the text to use SelectionColor or SelectionFont
For example: i want that all times that the word "hello" appear in the RichTextBox it turn to bold or turn into a color...
Then if i open my program and type "hello, how are you?" the word hello turns into bold... any idea? (my idea is to make a text editor with syntax highlight that ill specify the words)
(sorry if there is another question like that, i tried to search but i didn't find a answer that helped me)
its windows forms, visual basic
This code should do the work:
Dim searchstring As String = "hello"
' The word you're looking for
Dim count As New List(Of Integer)()
For i As Integer = 0 To richTextBox1.Text.Length - 1
If richTextBox1.Text.IndexOf(searchstring, i) <> -1 Then
'If the word is found
'Add the index to the list
count.Add(richTextBox1.Text.IndexOf(searchstring, i))
End If
Next
Try
For i As Integer = 0 To count.Count - 1
richTextBox1.[Select](count(i), searchstring.Length)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold)
count.RemoveAt(i)
Next
Catch
End Try
richTextBox1.[Select](richTextBox1.Text.Length, 0)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Regula
For each index select the text and make it bold.
Now add this code to the TextChanged-Event to check any time the text changed for your word.
I got it in a different way:
While Not RichTextBox1.Text.IndexOf("hello", startIndex) = -1
selectedIndex= RichTextBox1.SelectionStart
Try
RichTextBox1.Select(RichTextBox1.Text.IndexOf("test", startIndex) - 1, 1)
Catch
End Try
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex) + "test".Length, 1)
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex), "test".Length)
RichTextBox1.SelectionColor = Color.Blue
End If
End If
startIndex = RichTextBox1.Text.IndexOf("hello", startIndex) + "hello".Length
RichTextBox1.SelectionStart = selectedIndex
RichTextBox1.SelectionLength = 0
RichTextBox1.SelectionColor = Color.Black
End While
I don't know if it is the best way, but works.
That is a code for highlighting selected text at yellow (can be replaced by any other color), after finding it:
'find the text that need to be highlighted.
foundIndex = RichTextBox1.Find("hello", foundIndex + 1, -1, selectedFinds)
RichTextBox1.Focus()
If foundIndex = -1 Then
MessageBox.Show("This document don't contains the text you typed, or any of the text you typed as a whole word or mach case.", "Find Text Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
else
'now the text will be highlighted.
RichTextBox1.SelectionBackColor = Color.Yellow
Richtextbox1.focus
End If
I hope that code will help.
Private Sub RichTextBox1_DragOver(sender As Object, e As DragEventArgs) Handles RichTextBox1.DragOver
Dim p As Point
p.X = e.X
p.Y = e.Y
Dim num As Integer
Dim rightTXT As String
Dim leftTXT As String
Dim textpart As String
Dim TSelect As Boolean
Dim curpos As Integer = RichTextBox1.GetCharIndexFromPosition(RichTextBox1.PointToClient(p))
Dim PosStart As Integer
TSelect = False
If e.Data.GetDataPresent(DataFormats.StringFormat) Then
e.Effect = DragDropEffects.All
Try
leftTXT = Microsoft.VisualBasic.Left(RichTextBox1.Text, curpos)
If InStr(leftTXT, "%", CompareMethod.Text) Then
rightTXT = Microsoft.VisualBasic.Right(RichTextBox1.Text, Len(RichTextBox1.Text) - curpos)
If InStr(rightTXT, "%", CompareMethod.Text) Then
PosStart = curpos - InStr(StrReverse(leftTXT), "%") + 1
num = curpos + InStr(rightTXT, "%") - PosStart - 1
textpart = (RichTextBox1.Text.Substring(PosStart, num).TrimEnd)
Label3.Text = "mouse drag over:" + textpart
Label5.Text = num.ToString()
If ListBox1.Items.Contains(textpart) Then
TSelect = True
End If
End If
End If
Catch ex As Exception
Label4.Text = ex.ToString()
End Try
End If
If TSelect Then
Me.RichTextBox1.Select(PosStart - 1, num + 2)
wordSearch = RichTextBox1.SelectedText
Label4.Text = "word drag state: true"
match = True
Else
Label3.Text = "mouse drag over:"
Label4.Text = "word drag state: false"
Me.RichTextBox1.Select(0, 0)
End If
End Sub
I find the above codes to be too lengthy/complicated for a simple task...
Dim c As Integer = 0
Dim o As Integer = 0
Dim s As Integer = 0
Dim txt As String = RTB.Text
RTB.BackColor = Color.Black
Dim starts As Integer = 0
Do While txt.Contains(key) ' this avoids unnecessary loops
s = txt.IndexOf(key)
starts = s + o
RTB.Select(starts, key.Length)
RTB.SelectionBackColor = Color.Yellow
RTB.SelectionColor = Color.Blue
txt = txt.Substring(s + key.Length)
o += (s + key.Length)
c += 1
Loop
Me.Status.Text = c.ToString() & " found" ' and the number found