Abdul Jaja
Abdul Jaja

Reputation: 85

How should i handle Cannot access a disposed object exception when closing the program?

It happens while text is appending to richTextbox1 and i'm closing the program by clicking the red x on the form top right corner.

So i guess i need to handle this in the form closing event.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

}

This is where i'm updating the richTextBox(rtbPaths)

RichTextBoxExtensions.AppendText(rtbPaths, "Downloading: ", Color.Red);
RichTextBoxExtensions.AppendText(rtbPaths, downloader.CurrentFile.Path, Color.Green);
rtbPaths.AppendText(Environment.NewLine);

This is the RichTextBoxExtensions class

public class RichTextBoxExtensions
{
    public static void AppendText(RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }

    public static void UpdateText(RichTextBox box, string find, string replace, Color? color)
    {
        box.SelectionStart = box.Find(find, RichTextBoxFinds.Reverse);
        box.SelectionLength = find.Length;
        box.SelectionColor = color ?? box.SelectionColor;
        box.SelectedText = replace;
    }
}

TextChanged event

private void rtbPaths_TextChanged(object sender, EventArgs e)
{
    // set the current caret position to the end
    rtbPaths.SelectionStart = rtbPaths.Text.Length;
    // scroll it automatically
    rtbPaths.ScrollToCaret();
}

The exception message

Message=Cannot access a disposed object. Object name: 'RichTextBox'. ObjectName=RichTextBox Source=System.Windows.Forms StackTrace: at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.TextBoxBase.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.RichTextBox.get_TextLength() at DownloaderPro.Form1.RichTextBoxExtensions.AppendText(RichTextBox box, String text, Color color) in Form1.cs:line 249 at DownloaderPro.Form1.downloader_FileDownloadStarted(Object sender, EventArgs e) in Form1.cs:line 186

Upvotes: 1

Views: 1108

Answers (1)

MAHDI
MAHDI

Reputation: 24

Hi you can keep following code into closing event , it will prevent a disposing

e.Cancel = true;

Let me know if it did not work

Upvotes: 0

Related Questions