I have been trying to create a program that will find the word the user has clicked on, in a multiline textbox. This procedure is based on the index from the position of the click. The code I implemented:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
The problem is that whenever the program reaches the line:
previousCh = TextBox1.Text.Chars(previousIndex)
it exits with :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
While the exception is thrown, by hovering over the previousIndex variable visual studio shows me its value: -1.
I think that previousCh = " " condition never gets true, so the program never exits the while loop, which keeps looking for the previous character. At some point int previousIndex gets negative and the program crashes. Why does not the condtion work properly?
What is the problem?
Thank you.
If you do not want to have the user double click like David Wilson suggested (which i would also agree with) then this will get the result you want. It takes into account if the previous character is a line feed or the start of the text, or the next character is a line feed or end of the text as well. You can add to the If to find "," or "." if needed.
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
Dim startIndex As Integer = TextBox1.SelectionStart
Dim wordStartFound, wordEndFound As Boolean
Dim nextIndex, indexOfStartOfWord, indexOfEndOfWord, lengthOfWord As Integer
If Not startIndex = 0 Then
While Not wordStartFound
startIndex = startIndex - 1
If TextBox1.Text.Chars(startIndex) = " " Then
indexOfStartOfWord = startIndex + 1
wordStartFound = True
ElseIf startIndex = 0 Then
indexOfStartOfWord = startIndex
wordStartFound = True
ElseIf TextBox1.Text.Chars(startIndex) = Chr(10) Then 'Line Feed'
indexOfStartOfWord = startIndex + 1
wordStartFound = True
End If
End While
Else
indexOfStartOfWord = startIndex
End If
nextIndex = startIndex
While Not wordEndFound
nextIndex = nextIndex + 1
If TextBox1.Text.Chars(nextIndex) = " " Then
indexOfEndOfWord = nextIndex
wordEndFound = True
ElseIf nextIndex = TextBox1.TextLength - 1 Then
indexOfEndOfWord = TextBox1.TextLength
wordEndFound = True
ElseIf TextBox1.Text.Chars(nextIndex) = Chr(10) Then 'Line Feed'
indexOfEndOfWord = nextIndex
wordEndFound = True
End If
End While
lengthOfWord = indexOfEndOfWord - indexOfStartOfWord
Label2.Text = TextBox1.Text.Substring(indexOfStartOfWord, lengthOfWord)
End If
End Sub
Also in your function GetWordByIndex you split the input string into an array
Dim words = input.Split(" ")
then you say
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
but when you call .length on an array it returns the number of strings (or whatever is in the array) For example if the input was "The big brown fox jumped over the lazy dog", words.length - 1 will return 8. So if your index you pass through is the start of the word "over" it would fall into the Throw New IndexOutOfRangeException("Index out of range!") as the index would be 26 which is obviously greater than 8.
The code i have provided doesn't use the function to find the word but i thought i would mention that anyway.
Related
I want to highlight the text inside the text Box when a "#" is typed followed by any character as Facebook does. I tried to use SelectionStart ,SelectionLength and SelectionBackColor properties but I am facing many problems.
I need a help, what is the best event to handle the characters that are being typed? I used TextChanged event but its not working will. And is there another properties instead of SelectionStart and SelectionLength?
Please just give me tips and I will search.
I searched a lot but not finding useful topics.
Unfortunately, I don't think there is a way to do that with vb.net as it requires a postback to the server to run. In order to have it highlight the text as the user types you would need a frontend script to run.
Here is a link that may be helpful: https://forums.asp.net/t/1597892.aspx?Highlight+text+in+a+textbox
I made it !
Its working :) ...
This code detect hashtag entered by user and color it with green, also when the number of char exceed 140 it start highlighting them with red.
I used the KeyPress event instead of textChanged.
Public Class Form1
Dim previous As Char = " "
Dim indexOfHash As Integer = -1
Dim extraChar As Integer = 0
Private Const charLimit As Integer = 140 ' maximum char allowed in the textbox
Private Sub RichTextBox_keyPressed(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox.KeyPress
Try
Dim remainingCharCount As Integer
Dim textBoxLength As Integer = RichTextBox.TextLength
' if input is BACKSPACE
If (Not String.IsNullOrEmpty(e.KeyChar) AndAlso Asc(e.KeyChar) = 8) Then
remainingCharCount += 1
End If
remainingCharCount = charLimit - RichTextBox.TextLength
charRemainingLabel.Text = remainingCharCount & " Characters Left"
If remainingCharCount < 0 Then
extraChar += 1
Dim temp As Integer = RichTextBox.SelectionStart
RichTextBox.SelectionStart = RichTextBox.TextLength
RichTextBox.SelectionLength = remainingCharCount * -1
RichTextBox.SelectionBackColor = Color.LightCoral
RichTextBox.SelectionColor = Color.Black
charRemainingLabel.Text = String.Empty
charMinusLabel.Text = remainingCharCount & " Characters"
RichTextBox.SelectionStart = temp
ElseIf remainingCharCount >= 0 AndAlso extraChar > 0 Then
Dim temp As Integer = RichTextBox.SelectionStart
RichTextBox.SelectionStart = RichTextBox.TextLength
RichTextBox.SelectionLength = extraChar
RichTextBox.SelectionBackColor = Color.Transparent
RichTextBox.SelectionColor = Color.Black
RichTextBox.SelectionStart = temp
extraChar = 0
End If
Dim input As Char = e.KeyChar
Dim inputAsInteger As Integer = Asc(e.KeyChar)
previous = RichTextBox.GetCharFromPosition(RichTextBox.GetPositionFromCharIndex(RichTextBox.TextLength))
' if Hash and preceeded with SPACE or ENTER
If (Not String.IsNullOrEmpty(input) AndAlso input = "#" AndAlso (previous = " " Or String.IsNullOrEmpty(previous) Or previous = vbLf Or Asc(previous) = 13 Or RichTextBox.TextLength = 0)) Then
indexOfHash = RichTextBox.TextLength
End If
' if Hash exists STOP when find SPACE or ENTER
If indexOfHash <> -1 AndAlso (input = " " Or String.IsNullOrEmpty(input) Or Asc(input) = 13 Or input = vbLf) AndAlso (RichTextBox.TextLength - indexOfHash) > 1 Then
RichTextBox.SelectionStart = indexOfHash
RichTextBox.SelectionLength = RichTextBox.TextLength - indexOfHash
RichTextBox.SelectionColor = Color.Green
RichTextBox.SelectionStart = RichTextBox.TextLength
'RichTextBox.DeselectAll()
RichTextBox.SelectionColor = Color.Black
indexOfHash = -1 ' end of HashTag
End If
' if input is BACKSPACE
If (Not String.IsNullOrEmpty(input) AndAlso Asc(input) = 8 AndAlso (previous = "#")) Then
indexOfHash = RichTextBox.TextLength - 1
remainingCharCount += 1
End If
Catch ex As Exception
End Try
End Sub
end class
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
cfg file to start, this is the file:
http://pastebin.com/mE3Y3wiq
What I am doing is looking for a class, once found I store the data for THAT class in a listbox, so ex: if I'm looking for "Fixing", I will store each line in a listbox that is after "{Fixing}" until we hit the next class OR the end of the file (for Fixing we would stop at "{Pillars}")
Here is my code:
Private Sub tvList_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles tvList.AfterSelect
Dim cfgData() As String
' Dim lstData As New ListBox()
lstData.Items.Clear()
If rbnInch.Checked Then
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme_I\Dme_I.cfg")
Else
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme\Dme.cfg")
End If
Dim classID As Short = tvList.SelectedNode.Index
Dim classType As String = tvList.Nodes.Item(classID).Text
Try
For i As Short = 0 To cfgData.Count - 1
If cfgData(i).Contains("{" & classType & "}") Or cfgData(i).Contains("{" & classType.Replace(" ", "") & "}") Then
i += 1
Do
lstData.Items.Add(cfgData(i))
i += 1
If cfgData(i).Contains(tvList.Nodes.Item(tvList.SelectedNode.Index + 1).Text.Replace(" ", "")) Or cfgData(i).Contains(tvList.Nodes.Item(tvList.SelectedNode.Index + 1).Text) Or cfgData(i).ToString() Is vbNullString Then
Exit Do
End If
Loop
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Right now I am only getting the first line in my listbox and that's it. Need help on collecting the data I need and then stopping at the next class or end of file (end of file for the last class since there is no class after it that will mark my exit)
This has been extracted from the question and posted on the OP's behalf.
I solved it myself.
Private Sub tvList_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles tvList.AfterSelect
Dim cfgData() As String
' Dim lstData As New ListBox()
lstData.Items.Clear()
If rbnInch.Checked Then
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme_I\Dme_I.cfg")
Else
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme\Dme.cfg")
End If
Dim classID As Short = tvList.SelectedNode.Index
Dim classType As String = tvList.Nodes.Item(classID).Text
Try
For i As Short = 0 To cfgData.Count - 1
If cfgData(i).Contains("{" & classType) Or cfgData(i).Contains("{" & classType.Replace(" ", "")) Then
i += 1
Do
If tvList.SelectedNode.Index + 1 >= tvList.Nodes.Count Then
If i >= cfgData.Count - 1 Then
lstData.Items.Add(cfgData(i))
Exit Do
ElseIf cfgData(i) = vbNullString Then
lstData.Items.Add(cfgData(i))
i += 1
ElseIf cfgData(i).Substring(0, 1).Contains("{") Then
Exit Do
Else
lstData.Items.Add(cfgData(i))
i += 1
End If
ElseIf i >= cfgData.Count - 1 Then
lstData.Items.Add(cfgData(i))
Exit Do
ElseIf cfgData(i) = vbNullString Then
lstData.Items.Add(cfgData(i))
i += 1
ElseIf cfgData(i).Substring(0, 1).Contains("{") Then
Exit Do
Else
lstData.Items.Add(cfgData(i))
i += 1
End If
Loop
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am little bit confused in this program.
I am new to Visual Basic but intermediate to C.
Actually I want to get sub-string of string without using library function of Visual Basic.
Here is the C source code I also given my VB code too.
1.The Program will get two inputs from user i.e A & B
2. Than Find the substring from B.
3. Finally Print the result.
int i,j=0,k=0,substr=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]==b[j])
{
j++;
if(b[j]==0)
{
printf("second string is substring of first one");
substr=1;
break;
}
}
}
for(i=0;i<strlen(b);i++)
{
if(b[i]==a[k])
{
k++;
if(a[k]==0)
{
printf(" first string is substring of second string");
substr=1;
break ;
}
}
}
if(substr==0)
{
printf("no substring present");
}
While my code is
Dim a As String
Dim b As String
a = InputBox("Enter First String", a)
b = InputBox("Enter 2nd String", b)
Dim i As Integer
Dim j As Integer = 0
Dim k As Integer = 0
Dim substr As Integer = 0
For i = 0 To a.Length - 1
If a(i) = b(j) Then
j += 1
If b(j) = 0 Then
MsgBox("second string is substring of first one")
substr = 1
Exit For
End If
End If
Next i
For i = 0 To b.Length - 1
If b(i) = a(k) Then
k += 1
If a(k) = 0 Then
MsgBox(" first string is substring of second string")
substr = 1
Exit For
End If
End If
Next i
If substr = 0 Then
MsgBox("no substring present")
End If
End Sub
While compiling it gives following debugging errors.
Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17 24
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27 24
Part of your confusion is that .Net strings are much more than just character buffers. I'm going to assume that you can at least use strings. If you can't, use need to declare character arrays instead. That out of the way, this should get you there as a 1:1 translation:
Private Shared Function search(ByVal a As String, ByVal b As String) As Integer
Dim i As Integer = 0
Dim j As Integer = 0
Dim firstOcc As Integer
While i < a.Length
While a.Chars(i)<>b.Chars(0) AndAlso i < a.Length
i += 1
End While
If i >= a.Length Then Return -1 'search can not continue
firstOcc = i
While a.Chars(i)=b.Chars(j) AndAlso i < a.Length AndAlso j < b.Length
i += 1
j += 1
End While
If j = b.Length Then Return firstOcc
If i = a.Length Then Return -1
i = firstOcc + 1
j = 0
End While
Return 0
End Function
Shared Sub Main() As Integer
Dim a As String
Dim b As String
Dim loc As Integer
Console.Write("Enter the main string :")
a = Console.ReadLine()
Console.Write("Enter the search string :")
b = Console.ReadLine()
loc = search(a, b)
If loc = -1 Then
Console.WriteLine("Not found")
Else
Console.WriteLine("Found at location {0:D}",loc+1)
End If
Console.ReadKey(True)
End Sub
But please don't ever actually use that. All you really need is this:
Private Shared Function search(ByVal haystack as String, ByVal needle As String) As Integer
Return haystack.IndexOf(needle)
End Function
VB has a built-in function called InStr, it's part of the language. It returns an integer specifying the start position of the first occurrence of one string within another.
http://msdn.microsoft.com/en-us/library/8460tsh1(v=VS.80).aspx
Pete
Try this one, this will return a List(Of Integer) containing the index to all occurrence's of the find text within the source text, after the specified search starting position.
Option Strict On
Public Class Form1
''' <summary>
''' Returns an array of indexes where the find text occurred in the source text.
''' </summary>
''' <param name="Source">The text you are searching.</param>
''' <param name="Find">The text you are searching for.</param>
''' <param name="StartIndex"></param>
''' <returns>Returns an array of indexes where the find text occurred in the source text.</returns>
''' <remarks></remarks>
Function FindInString(Source As String, Find As String, StartIndex As Integer) As List(Of Integer)
If StartIndex > Source.Length - Find.Length Then Return New List(Of Integer)
If StartIndex < 0 Then Return New List(Of Integer)
If Find.Length > Source.Length Then Return New List(Of Integer)
Dim Results As New List(Of Integer)
For I = StartIndex To (Source.Length) - Find.Length
Dim TestString As String = String.Empty
For II = I To I + Find.Length - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then Results.Add(I)
Next
Return Results
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Search As String = "Hello world, this world is an interesting world"
Dim Find As String = "world"
Dim Indexes As List(Of Integer) = New List(Of Integer)
Try
Indexes = FindInString(Search, Find, 0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
RichTextBox1.Text = "Search:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Search & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Find:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Find & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "-----------" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Result Indexes:" & vbCrLf & vbCrLf
For Each i As Integer In Indexes
RichTextBox1.Text = RichTextBox1.Text & i.ToString & vbCr
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Here is another way, where there is no use of .Net functions.
Function FindInString(Source As String, Find As String, StartIndex As Integer) As Integer()
If StartIndex > Len(Source) - Len(Find) Then Return {}
If StartIndex < 0 Then Return {}
If Len(Find) > Len(Source) Then Return {}
Dim Results As Integer() = {}, ResultCount As Integer = -1
For I = StartIndex To Len(Source) - Len(Find)
Dim TestString As String = ""
For II = I To I + Len(Find) - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then
ResultCount += 1
ReDim Preserve Results(ResultCount)
Results(ResultCount) = I
End If
Next
Return Results
End Function
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