Home > Blockchain >  How can I save the content of a rich text box even when the form closes?
How can I save the content of a rich text box even when the form closes?

Time:03-23

This is my first post here, so please don't judge me if I write something wrong ^^

Anyways, I've recently run into an issue with richtextboxes in Visual Basic .NET and WinForms. Let's say I have a Main form and a Log form. The log form contains a richtextbox which functions as a log. From the main form I'm writing text to the log and I also format the lines, so they have different colors (blue for information, red for error). Unfortunately, whenever I close and reopen the log form all text that has been written to it is lost. I've tried saving it to a text file, but that doesn't save the colors of the text.

Is there any way I can save the text and the colors of the lines even when the form closes?

CodePudding user response:

Here's what the excellent suggestion from Shrotter might look like:

Public Class Form1

    Private RtfPath As String

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim folder As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
        RtfPath = System.IO.Path.Combine(folder, "RtbData.rtf")

        If System.IO.File.Exists(RtfPath) Then
            RichTextBox1.LoadFile(RtfPath)
        End If
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        RichTextBox1.SaveFile(RtfPath)
    End Sub

End Class

Of course, you should always wrap the loading/saving of the file in a Try/Catch block in case anything goes wrong.

  • Related