Why doesn't find function work in While statment - vb.net

I'm using a RichTextBox find function. It works fine until I stick it in a While loop. Then it won't do anything.
This code works:
Dim startTEXT As Integer = 0
Dim endTEXT As Integer = RichTextBox1.Text.LastIndexOf(tword)
While startTEXT < endTEXT
RichTextBox1.Find(tword, startTEXT, RichTextBox1.TextLength, RichTextBoxFinds.WholeWord)
RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont.FontFamily, RichTextBox1.SelectionFont.Size, FontStyle.Underline)
RichTextBox1.SelectionColor = Color.Red
startTEXT = RichTextBox1.Text.IndexOf(tword, startTEXT) + 1
End While
This code does not:
For Each tword In ListBox1.Items
Dim startTEXT As Integer = 0
Dim endTEXT As Integer = RichTextBox1.Text.LastIndexOf(tword)
While startTEXT < endTEXT
RichTextBox1.Find(tword, startTEXT, RichTextBox1.TextLength, RichTextBoxFinds.WholeWord)
RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont.FontFamily, RichTextBox1.SelectionFont.Size, FontStyle.Underline)
RichTextBox1.SelectionColor = Color.Red
startTEXT = RichTextBox1.Text.IndexOf(tword, startTEXT) + 1
End While
Next
What is preventing the find function from working?
Using VB.NET 2010.

Related

Import very big text file into sql. Speed problem

I must import a big text file into sql database.
The text file contains some 5 million of rows. :D
My pc is old ed I use vb.net, but is only for one shot.
When import started, the code read and entered 100 lines for second.
Is slowly but for one shot is not a problem.
Now, at 300.000 lines readed, it work ar 8 lines for second. :(
The goal is far away....
The strange thing is, if I start from first line and in the database have 300.000 record, the speed is fast (100 L/s) even though I check that I don't have the record.
In sql I created a cluster index.
This is the vb.net code into BackgroundWorker DoWork:
Private Sub Bw_DoWork(sender As Object, e As DoWorkEventArgs)
Dim d = DirectCast(e.Argument, BwData).Path
Dim s = DirectCast(e.Argument, BwData).Start
Dim reader As IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(d)
Dim l As String
Dim lineIndex As Integer = 0
Dim lineStart As Integer = 0
Dim part As String() = Nothing
Try
Using ctx = New ContentsDBEntities
Dim rowN = s 'Math.Max(ctx.xHamster.Count - 100, 1)
Do
l = reader.ReadLine
If l Is Nothing Then
Exit Do
End If
part = l.Split("|")
If Bw.CancellationPending Then Exit Do
If lineIndex >= rowN AndAlso part.Length >= 14 Then
If lineIndex = rowN Then
lineStart = lineIndex
startAt = Now
End If
Dim vId = part(0)
If IsNumeric(vId) Then
Dim there = (From c In ctx.xHamster Where c.VideoId = vId Select c).FirstOrDefault
If there Is Nothing Then
Dim r = New xHamster With {
.VideoId = vId,
.Url = part(1),
.Umbed_Url = part(2),
.Title = part(3),
.Duration = StringToSec(part(4)),
.dateAdded = Date.Parse(part(5)),
.Thumb = part(6),
.Channels = part(7),
.Pornstars = part(8),
.MaxResolution = part(9),
.Orientation = part(10),
.Title_RU = part(11),
.Username = part(12),
.Description = part(13)}
ctx.xHamster.Add(r)
If lineIndex Mod 100 = 0 Then
ctx.SaveChanges()
End If
End If
End If
End If
lineIndex += 1
DirectCast(sender, BackgroundWorker).ReportProgress(lineIndex, lineStart)
Loop Until l Is Nothing
reader.Close()
ctx.SaveChanges()
End Using
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
Do you have a trick for me?
Why does the speed decrease?
Thank you
Luca

vb.net readalllines fill form replace certain lines coding advice

What I'm trying to accomplish is reading a text file and selecting certain lines to modify by filling in text from a second form. Here is an example the code I'm currently using. What's happening is I'm looking for a line that starts with 718 and then somewhere after that line there will be a line that starts with 720. I need both lines to fill in the second form. The only way I can think of is to just keep adding 1 to the line until it reaches the line I need. I'm still new to this and I'm sure there's an easier way to do this maybe using Try or While but I'm not sure how. Appreciate any help.
Dim lines() As String = File.ReadAllLines(tempsave)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("718") Then
If lines(i + 1).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 1).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array(3), FormFill.TextBox1.Text)
lines(i + 1) = lines(i + 1).Replace(array(9), FormFill.TextBox2.Text)
Else
If lines(i + 2).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 2).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array2(3),FormFill.TextBox1.Text)
lines(i + 2) = lines(i + 2).Replace(array(9), FormFill.TextBox2.Text)
End If
End If
End If
Next
Example Data:
Input:
123*test*test*test~
718*test*test*test~
543*test*test*test~
720*test*test*test~
Output:
123*test*test*test~
718*test*test*newdata~
543*test*test*test~
720*test*test*newdata~
Here, try this:
Public Sub Lines()
Dim _
aNextLines,
aAllLines As String()
Dim _
s718Line,
s720Line As String
aAllLines = IO.File.ReadAllLines("D:\Logs\Data.log")
For i As Integer = 0 To aAllLines.Length - 1
If aAllLines(i).StartsWith("718") Then
s718Line = aAllLines(i)
aNextLines = aAllLines.Skip(i + 1).ToArray
s720Line = aNextLines.FirstOrDefault(Function(Line) Line.StartsWith("720"))
' Process data here
End If
Next
End Sub
--UPDATE--
Here's a modified version that both reads and writes:
Public Sub Lines()
Dim oForm As FormFill
Dim _
aNextLines,
aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
oForm = New FormFill
aAllLines = IO.File.ReadAllLines(oForm.FilePath)
s718Line = String.Empty
s720Line = String.Empty
For i718Index = 0 To aAllLines.Length - 1
If aAllLines(i718Index).StartsWith("718") Then
s718Line = aAllLines(i718Index)
aNextLines = aAllLines.Skip(i718Index + 1).ToArray
For i720Index = 0 To aNextLines.Length - 1
If aNextLines(i720Index).StartsWith("720") Then
s720Line = aNextLines(i720Index)
Exit For ' Assumes only one 720 line in the file
End If
Next
Exit For ' Assumes only one 718 line in the file
End If
Next
oForm.TextBox718.Text = s718Line
oForm.TextBox720.Text = s720Line
oForm.TextBox718.Tag = i718Index
oForm.TextBox720.Tag = i720Index
End Sub
Now, in your Save button's Click event handler:
Private Sub SaveButton_Click(Sender As Button, e As EventArgs) Handles SaveButton.Click
Dim aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
s718Line = Me.TextBox718.Text
s720Line = Me.TextBox720.Text
i718Index = Me.TextBox718.Tag
i720Index = Me.TextBox720.Tag
aAllLines = IO.File.ReadAllLines(Me.FilePath)
aAllLines(i718Index) = s718Line
aAllLines(i720Index) = s720Line
IO.File.WriteAllLines(Me.FilePath, aAllLines)
End Sub
That should do it.

Pasting data into a DataGridView vb.net

So this morning I ran into a wall:
Using this Code I randomly get another row to show up when i paste my data.
It is meant to receive values ranging from 1 to 99999
So when i copy this:
And paste it into the Program this happens:
Private Sub DataGridView101_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView101.KeyDown
If e.Control And
e.KeyCode = Keys.V Then
IsCopyPaste = True
Dim _ClipboardRows As String() = System.Windows.Forms.Clipboard.GetText().Split({System.Environment.NewLine}, StringSplitOptions.None)
Me.DataGridView101.BeginEdit(True)
For Each _ClipboardRow As String In _ClipboardRows
If _ClipboardRow <> "" Then
Dim _CellL As String = ""
Dim _CellR As String = ""
For Each _ClipboardColumn As String In _ClipboardRow.Split(System.Convert.ToChar(vbTab))
If _CellL = "" Then
_CellL = _ClipboardColumn
Else
If _CellR = "" Then
_CellR = _ClipboardColumn
End If
End If
Next
Dim _DataRow As System.Data.DataRow = (CType(Me.DataGridView101.DataSource, System.Data.DataTable)).NewRow()
_DataRow("1") = _CellL
_DataRow("2") = _CellR
CType(Me.DataGridView101.DataSource, System.Data.DataTable).Rows.Add(_DataRow)
End If
Next
Me.DataGridView101.EndEdit()
CType(Me.DataGridView101.DataSource, System.Data.DataTable).AcceptChanges()
IsCopyPaste = False
End If
End Sub
Below is my solution for that. You must call the functions from your event. In my application I need to decide allow pasting or not in the PasteUnboundRecords sub, which is controlled by the Allowed boolen
Public Sub CopyRows(MyDataGridView As DataGridView)
Dim d As DataObject = MyDataGridview.GetClipboardContent()
Try
Clipboard.SetDataObject(d)
Catch
MessageBox.Show("Text not copied, null value")
End Try
End Sub
Sub PasteUnboundRecords(MyDataGridView As DataGridView)
Dim Allowed As Boolean
Dim OriginLines As String() = Clipboard.GetText(TextDataFormat.Text).Split(New String(0) {vbCr & vbLf}, StringSplitOptions.None)
Dim Xo As Integer = SelectedAreaMinColumn(MyDataGridview)
Dim Yo As Integer = SelectedAreaMinRow(MyDataGridview)
Dim X As Integer
Dim Y As Integer
Dim i As Integer
Dim j As Integer
Dim ii As Integer
Dim jj As Integer = 0
Dim m1 As Integer
Dim n1 As Integer = OriginLines.Length
Dim m2 As Integer = SelectedAreaColumns(MyDataGridView)
Dim n2 As Integer = SelectedAreaRows(MyDataGridview)
Dim m2Max As Integer = MyDataGridview.Columns.Count
Dim n2Max As Integer = MyDataGridview.Rows.Count
For j = 0 To Math.Max(n1-1, n2-1)
Y = Yo + j
If Y = n2Max Then Exit For
If j-jj*n1 = n1 Then jj = jj+1
Dim OriginValue As String() = OriginLines(j-jj*n1).Split(New String(0) {vbTab}, StringSplitOptions.None)
m1 = OriginValue.Length
ii = 0
For i = 0 To Math.Max(m1-1, m2-1)
X = Xo + i
If X = m2Max Then Exit For
If i-ii*m1 = m1 Then ii = ii+1
If X > 0 Then 'Avoid pasting in first column containing codes
If Y = 0 Then 'Avoid first line
Allowed = True
Else 'Check DataValidatios
If DataValidations(OriginValue(i-ii*m1), X) = "OK" Then
Allowed = True
Else
Allowed = False
End If
End If
'Avoid pasting in Readonly columns
If MyDataGridview.Rows(Y).Cells(X).ReadOnly Then
Allowed = False
End If
If Allowed Then
MyDataGridview.Rows(Y).Cells(X).Value = OriginValue(i-ii*m1)
End If
End If
End If
Next i
Next j
End Sub
Private Function SelectedAreaMinRow(MyDataGridView As DataGridView) As Integer
Dim minRowIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
End If
minRowIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).RowIndex, minRowIndex)
Next i
Return minRowIndex
End Function
Private Function SelectedAreaMinColumn(MyDataGridView As DataGridView) As Integer
Dim minColumnIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
End If
minColumnIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).ColumnIndex, minColumnIndex)
Next i
Return minColumnIndex
End Function
Private Function SelectedAreaRows(MyDataGridView As DataGridView) As Integer
Dim minRowIndex As Integer
Dim MaxRowIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
MaxRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
End If
minRowIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).RowIndex, minRowIndex)
MaxRowIndex = Math.Max(MyDataGridView.SelectedCells.Item(i).RowIndex, MaxRowIndex)
Next i
Return MaxRowIndex-minRowIndex+1
End Function
Private Function SelectedAreaColumns(MyDataGridView As DataGridView) As Integer
Dim minColumnIndex As Integer
Dim MaxColumnIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
MaxColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
End If
minColumnIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).ColumnIndex, minColumnIndex)
MaxColumnIndex = Math.Max(MyDataGridView.SelectedCells.Item(i).ColumnIndex, MaxColumnIndex)
Next i
Return MaxColumnIndex-minColumnIndex+1
End Function

RichTextBox flikers when syntax highlight

I am writing an IDE an while working on syntax highlighting, i've encountered a very annoying issue.
When I type something, the text flickers...
Here is my code:
Dim KeyWords As List(Of String) = New List(Of String)(New String() {"void", "int", "long", "char", "short", "unsigned", "signed", "#include", "#define", "return"})
Dim KeyWordsColors As List(Of Color) = New List(Of Color)(New Color() {Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Olive, Color.Olive, Color.Blue})
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim words As IEnumerable(Of String) = RichTextBox1.Text.Split(New Char() {" "c, ".", ",", "?", "!", "(", Chr(13), Chr(10), " "})
Dim index As Integer = 0
Dim rtb As RichTextBox = sender 'to give normal color according to the base fore color
For Each word As String In words
'If the list contains the word, then color it specially. Else, color it normally
'Edit: Trim() is added such that it may guarantee the empty space after word does not cause error
coloringRTB(sender, index, word.Length, If(KeyWords.Contains(word.ToLower().Trim()) Or KeyWords.Contains("<"), KeyWordsColors(KeyWords.IndexOf(word.ToLower().Trim())), rtb.ForeColor))
index = index + word.Length + 1 '1 is for the whitespace, though Trimmed, original word.Length is still used to advance
Next
Dim strings() As String = RichTextBox1.Text.Split(Chr(34))
Dim count As Integer = 0
Dim cpart As Integer = 0
For Each part In strings
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
Dim strings2() As String = RichTextBox1.Text.Split(New Char() {"<", ">"})
count = 0
cpart = 0
For Each part In strings2
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
End Sub
Private Sub coloringRTB(rtb As RichTextBox, index As Integer, length As Integer, color As Color)
Dim selectionStartSave As Integer = rtb.SelectionStart 'to return this back to its original position
rtb.SelectionStart = index
rtb.SelectionLength = length
rtb.SelectionColor = color
rtb.SelectionLength = 0
rtb.SelectionStart = selectionStartSave
rtb.SelectionColor = rtb.ForeColor 'return back to the original color
End Sub
Private Sub RichTextBox1_KeyUp(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If e.KeyChar = "{"c Then
RichTextBox1.SelectedText = "{}"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("{") + 1
e.Handled = True
End If
If e.KeyChar = "("c Then
RichTextBox1.SelectedText = "()"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("(") + 1
e.Handled = True
End If
If e.KeyChar = "["c Then
RichTextBox1.SelectedText = "[]"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("[") + 1
e.Handled = True
End If
If e.KeyChar = "'"c Then
RichTextBox1.SelectedText = "''"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("'")
e.Handled = True
End If
Dim currentLength = RichTextBox1.Text.Length
End Sub
hope someone can help Thanks ^_^
RichTextBox1 is the richtextbox

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