Mr Arman
Mr Arman

Reputation: 91

replace a line in richtextbox vb.net

I have this code but it have errors , what should i do ?

         Dim lines As New List(Of String)
    lines = RichTextBox1.Lines.ToList
    'Dim FilterText = "@"

    For i As Integer = lines.Count - 1 To 0 Step -1
        'If (lines(i).Contains(FilterText)) Then
        RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("@", "@sometext")
        'End If
    Next

    RichTextBox1.Lines = lines.ToArray

Upvotes: 1

Views: 2720

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460098

Update: while the following "works" it does only modify the array which was returned from the Lines-property. If you change that array you don't change the text of the TextBox. So you need to re-assign the whole array to the Lines-property if you want to change the text(as shown below). So i keep the first part of my answer only because it fixes the syntax not the real issue.


It's not

RichTextBox1.Lines(i).Replace = "@sometext"

but

RichTextBox1.Lines(i) =  "@sometext"

You can loop the Lines forward, the reverse loop is not needed here.


Maybe you want to replace all "@" with "@sometext" instead:

RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("@","@sometext")

So here the full code necessary (since it still seems to be a problem):

Dim newLines As New List(Of String)
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
    newLines.Add(RichTextBox1.Lines(i).Replace("@", "@sometext"))
Next
RichTextBox1.Lines = newLines.ToArray()

But maybe you could even use:

RichTextBox1.Text = RichTextBox1.Text.Replace("@","@sometext")`

because if we have @ abcd this code change it to @ sometextabcd ! I Want a code to replace for example line 1 completely to @ sometext

Please provide all relevant informations in the first place next time:

Dim newLines As New List(Of String)
For Each line As String In RichTextBox1.Lines
    Dim newLine = If(line.Contains("@"), "@sometext", line)
    newLines.Add(newLine)
Next
RichTextBox1.Lines = newLines.ToArray()

Upvotes: 4

Related Questions