Detect NewLine/vbCr/vbLf at end of RichTextBox text

Winforms app in VB.Net...

I have a richtextbox, RTB1.  I need to check to see if the user has pressed Enter at the very end of the RTB1 contents, and if not, I need to add a new line at the end, using...

RTB1.AppendText(vbCr) or RTB1.AppendText(environment.NewLine)

I have tried the following:

 >> Attempt1
If Not RTB1.Rtf.EndsWith(ControlChars.Cr) Then
txtFilenotes.AppendText(ControlChars.Cr)
End If

 >>Attempt2
If Not RTB1.Text.EndsWith(ControlChars.Cr) Then
txtFilenotes.AppendText(ControlChars.Cr)
End If

 >>Attempt3
If Not RTB1.Text.EndsWith(Environment.NewLine) Then
txtFilenotes.AppendText(Environment.NewLine)
End If

.....without success.

Please help

TIA
LVL 1
Sigh_ManAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Sigh_ManAuthor Commented:
NB - 'txtFilenotes' and RTB1 should be the same.  For example, the code in Attempt 3 should read...

If Not RTB1.Text.EndsWith(Environment.NewLine) Then
RTB1.AppendText(Environment.NewLine)
End If

0
arif_eqbalCommented:
       If RTB1.Text.EndsWith(vbLf) Then
            MsgBox("Yes")
        Else
            RTB1.Text = RTB1.Text & vbCrLf
        End If
0
arif_eqbalCommented:
Hi Sigh_Man
It might appear to be a bit strange but if you search the Text for VBCrLf or even VBCr you'd see that it won't find any

RTB1.Text.Indexof(vbcr) will always be -1

Actually its like, the combination of VBCr and VBLf which signifies a proper New Line (equivalent to VBCrLf) is translated implicitly and the VBCr is lost only VBLf is preserved so you can only look for it. However for Appending you must use both i.e.
RTB1.AppendText(VBLf) will not work you need to use RTB1.AppendText(VBCrLf)

Look what the documentation has to say... (remember \r=VBCr and \nVBLf)

In Windows you have to pass multi-line strings with \r\n, otherwise the system functions don't recognize them correctly as multi-line. This is true e.g. for setting the text of Edit controls, Labels, Windows etc. Also, when you read multi-line text from a file that initially contains "\r\n" in translated mode, the string in memory will contain only a single "\n".

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Sigh_ManAuthor Commented:
Arif

If RTB1.Text.EndsWith(vbLf) Then....... does not work.  I made sure that I hit enter on saving my RTB, but when I ran this code it did not say Yes, despite the content of the RTB ending with 'Enter'.

Also, the second part of the code simply removes all text and shows only the vbCrLf.  I can sort something out with this second part but please re-think the first bit.

Thanks   :D
0
arif_eqbalCommented:
strange
I have a richTextBox I enter som etext then hit ENTER key

Then I click on a button which runs this code
       If RTB1.Text.EndsWith(vbLf) Then
            MsgBox("Yes")
        Else
            RTB1.Text = RTB1.Text & vbCrLf
        End If

And it certainly shows the messagebox
Also in case I do not hit Enter first time it will not show the msgbox but a click again will show "YES"

Anyway I'd just try some other way of doing it....
0
arif_eqbalCommented:
Your ultimate aim is that if there is no newLine at the End we should programatically Add one isn't it ??

Even this will do it

RTB1.Text = RTB1.Text.TrimEnd(vbCr, vbLf)
RTB1.AppendText(vbCrLf)

But I still wonder why the earlier thing did not work try checking the Indexof VBLF and see if you get it...
I can not do it as I am not having this problem here
0
Sigh_ManAuthor Commented:
Thanks - I'll try that right now...
0
Sigh_ManAuthor Commented:
Just to let you know, my RTB contained the following:

Line 1 - testing
Line 2 - testing
Line 3 - further testing

Even when I delete everything after "further testing", the answer ...IndexOf(vbLf) says "Yes".  Presumably this is due to each line being seen as a vbLf.  Actually, even if I have one line of text, ...IndexOf(vbLf) says "Yes"

Any ideas?

0
Sigh_ManAuthor Commented:
...Actually, even if the RTB is empty, the ...IndexOf(vbLf) says "Yes"     :-/
0
arif_eqbalCommented:
Well Indexof returns an Integer value
it should return -1 if not found
so check your code

if RTB1.Text>IndexOf(vbLf) > -1 Then
   Msgbox "Found"
Else
   Msgbox "Not Found"
End If

try this...
0
Sigh_ManAuthor Commented:
It is not finding vbLf even though the RTB contains several instances of them.
Nor does it find vbCrLf or vbCr.

(it says "Not found")
0
Sigh_ManAuthor Commented:
(There was a mistake in my earlier code, which I have now corrected)
0
arif_eqbalCommented:
So is it working now...
0
Sigh_ManAuthor Commented:
No, I am looking to see if I can make this work by reference to the \par in the RTB's .rtf property.

I had a similar problem to this with RTBs -- I could easily do AppendText(vbLf) but AppendText(vbBack) would not work (instead of deleting it would add a small black line to the RTB.  I don't know if these issues are connected, but suffice it to say that I don't like RTB's behaviour!

I'll post something as soon as I've worked out some code.
0
Sigh_ManAuthor Commented:
No, this is horrible -- I cannot get this to work.

Please help!!    :D
0
arif_eqbalCommented:
Could you post some of your code
0
Sigh_ManAuthor Commented:
OK, you I have posted a stack of code below.  You will note that it is all commented out.  This is because I have been trying all afternoon to get this working, and rather than deleting it, I can see what my previous attempts were.

I thought some of my efforts appeared perfectly logical, but ..... evidently not!!

I hope you can fix this.

Thanks again.

PS - I'm logging off shortly - but will respond to any comments asap!


Here's the code...

'If RTB1.Text.EndsWith(Environment.NewLine) And CType(RTB1, RichTextBox).Lines.GetUpperBound(0) > 1 Then
        'MsgBox("Environment.NewLine detected successfully")
        'RTB1.AppendText(Environment.NewLine)
        'End If


        'RTB1.AppendText(Environment.NewLine)

        'Dim FNLinesArray As ArrayList
        'FNLinesArray.Add()

        'Dim originalText As String
        'originalText = RTB1.Text
        '

        'If RTB1.Text.IndexOf(vbCrLf) Then MsgBox("Yes")
        'Else
        'RTB1.Text = originalText & vbCrLf
        'End If

        'RTB1.Text = RTB1.Text.TrimEnd(vbCr, vbLf)

        'If RTB1.Text.IndexOf(vbLf) > -1 Then
        'If RTB1.Text.IndexOf(vbCrLf) > -1 Then
        'If RTB1.Text.IndexOf(vbCr) > -1 Then
        'If RTB1.Text.IndexOf(v) > -1 Then

        'If RTB1.Rtf.EndsWith("\par") Then MsgBox("Found \par")
        'If RTB1.Rtf.EndsWith("\par\par") Then MsgBox("Found \par\par")
        'If RTB1.Rtf.EndsWith("\par \par") Then MsgBox("Found \par \par")

        'Dim IndexOfLastPar As Integer = RTB1.Rtf.LastIndexOf("\par")
        'MsgBox(IndexOfLastPar)

        'Dim lengthOfFilenote As Integer = RTB1.Rtf.Length
        'MsgBox(lengthOfFilenote)

        'Dim paraPenultimateSubstringStart As Integer = lengthOfFilenote - (lengthOfFilenote - indexoflastpara)
        'MsgBox(RTB1.Rtf.Substring(IndexOfLastPar - 6, 4))

        'If indexoflastpara - paraPenultimateSubstringStart < 5 Then
        'MsgBox("Yes, there is a blank line at the end")
        'Else
        'MsgBox("No, there is no blank line at the end")
        'End If


       
        'Dim lengthOfFilenote As Integer = RTB1.Rtf.Length
        'MsgBox(lengthOfFilenote)
        'MsgBox(RTB1.Rtf.Substring(lengthOfFilenote - 6, 4))
        'MsgBox(RTB1.Rtf.Substring(lengthOfFilenote - 10, 4))


        'if RTB1.Rtf.Substring(IndexOfLastPar - 6, 4) = "\par" and

        'MsgBox(RTB1.Rtf.LastIndexOf("\par"))
        'MsgBox(RTB1.Rtf.Length)

        'MsgBox(RTB1.Rtf.ToString)



        ' NEXT LINE IS OK
        'RTB1.AppendText(vbCrLf)




        'MsgBox(RTB1.Lines.GetUpperBound(0) & " lines")


        'If Not RTB1.Rtf.EndsWith("\par") Then
        'RTB1.AppendText(Environment.NewLine)
        'End If

        'MsgBox(RTB1.Rtf.ToString.LastIndexOf("\par"))
        'MsgBox(RTB1.Rtf.LastIndexOf(vbCr)) ' 230
        'MsgBox(RTB1.Rtf.LastIndexOf(Environment.NewLine)) ' 230
        'MsgBox(RTB1.Text.LastIndexOf(vbCr)) ' -1
        'MsgBox(RTB1.Text.LastIndexOf(Environment.NewLine)) ' -1
        'MsgBox(RTB1.Rtf.Length()) ' 233

        'If Not RTB1.Rtf.ToString.LastIndexOf("\par") = (RTB1.Rtf.Length() - 10) Then
        'RTB1.AppendText(ControlChars.NewLine)
        'RTB1.Text += vbCr
        'End If



        'LastLine = RTB1.Text.LastIndexOf(

        'If RTB1.Text Then

        'End If


        'LastLineNumber = RTB1.Lines. 'GetLength(((1) '.GetUpperBound(0)
        'MsgBox(LastLineNumber)

        'LastLine = CType(RTB1, RichTextBox).Lines(LastLineNumber)
        'MsgBox("!" & LastLine & "!")

        'If LastLine.Length > 0 Then ' Is Nothing Then '= "" Then 'environment.NewLine Then
        'RTB1.AppendText(Environment.NewLine)
        'End If

        '    If Not RTB1.Rtf.EndsWith(ControlChars.Cr) Then
        ' if rtbcontent ends with blank line then do nothing
        ' else put a blank line at the end...
        'RTB1.AppendText(ControlChars.Cr)
        'End If
0
RonaldBiemansCommented:
Hi sigh_man,

try this

        If not RichTextBox1.Lines((RichTextBox1.Lines.Length - 1)) = "" Then
            RichTextBox1.AppendText(Environment.NewLine)
        End If
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
arif_eqbalCommented:
Hi Sigh_Man
Is your RTB empty in the beginning, did you test either of the code RonaldBiemans or mine on a fresh form.
Because both of them work fine for me, there must be something there...
0
Sigh_ManAuthor Commented:
Thanks guys....

OK, I'm sorry to give the experts the runaround on this, but I think I have made a stupid mistake.  Very embarrassing.  I was trying the execute this code on the Form's Deactivate event, which (I assume) is messing up the index values etc.  How can I catch the user's clicking on the form_close 'x' button and execute this code prior to closing the form?
0
arif_eqbalCommented:
Use Form_Closing event

    Private Sub Frm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If RTB1.Text.EndsWith(vbLf) Then
            MsgBox("Exists")
        Else
            RTB1.AppendText(vbCrLf)
            MsgBox("Added")
        End If
    End Sub
0
Sigh_ManAuthor Commented:
Excellent.  Thanks both!    :D
0
Sigh_ManAuthor Commented:
I hope you're both OK with the points split.  The accepted answer above is the only one that stood up to loads of testing.

Arif, thanks for your continued help - perhaps in a different scenario (ie if my program wasn't so crazy in its design!) I'm sure your solution(s) would have been best.  I have given you most points (in fact, the same amount as was first allocated to this question) despite RB's answer being the accepted one.  (I think the idea of EE is to accept the code that solves my problem - for the benefit of other EE members - I hope you're OK with this - if not, I'll have to remember you for some extra points next time!!).  The points is what matters most.

Phew!!

Thanks again   :D
0
arif_eqbalCommented:
Hi sigh Man
In case you are using RonaldBiemans solution
just add one line before it
If RTB1.Lines.Length > 0 Then
    .....

Or make it like this

      If RTB1.Lines.Length > 0 AndAlso Not RTB1.Lines((RTB1.Lines.Length - 1)) = "" Then
            RTB1.AppendText(Environment.NewLine)
      End If

This is in case your RTB is empty the compiler should not give IndexOutofRange Error as we are using "Length-1" here

Thanks
0
Sigh_ManAuthor Commented:
RB - I hope you're OK with this - since you've helped me out in about two thirds of my postings!!   :D
0
arif_eqbalCommented:
hi Sigh_Man
Its perfectly fine, RonaldBiemans of course deserved it
we were only looking at the problem from one angle (VbCr, VbCrLf ....)
He gave a better alternative....
0
RonaldBiemansCommented:
Ok by me, as long as your problem was solved :-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.