Search code examples
c#winforms.net-8.0

In a C# Windows Form how should I unsubscribe from events in the code behind given that I dont want to modify code in the designer?


A C# Windows form has the generated dispose method code in it's designer File

partial class DetailRibbonForm2
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
   // etc

I want to add some code to the code behind file that will unsubscribe from events at dispose time.

How do I do this?

If I try to override Dispose in the Code Behind I get

error CS0111: Type 'DetailRibbonForm2' already defines a member called 'Dispose' with the same parameter types


Solution

  • Did you try just putting your custom dispose logic in that existing method? Note that it is "not" within the #region Windows Form Designer generated code block and therefore shouldn't get overwritten. It's just another member method of DetailRibbonForm2. In fact, you can move it from DetailRibbonForm2.Designer.cs to DetailRibbonForm2.cs without penalty if you prefer.