Search code examples
c#switch-statementobjectdisposedexception

ObjectDisposedException - Control declared, unabe to access control


I am trying to make some code more concise and am throwing an exception when I try to, I suppose, dynamically define a control. Whichever way I try, a and b always return as disposed. I could separate the cases out, but that would make the code twice as long. Any suggestion/comments would be much appreciated.

foreach (string[] str in items)
            {
                Control box = new Control();
                CustomControlTypeA a = CustomControlTypeA();
                CustomControlTypeB b = new CustomControlTypeB();
                switch (str[4])
                {
                    case "0":
                        a.richTextBox1.Rtf = str[5];
                        box = a;
                        break;

                    case "1":
                        b.panel1.BackgroundImage = Image.FromFile(str[5]);
                        box = b;
                        break;
                }
                a.Dispose();
                b.Dispose();
                box.Location = new Point(x,y);
                box.Width = w;
                box.Height = h;
                panelBody.Controls.Add(box);
                box.BringToFront();
            } 

I also tried defining CustomControlTypeA inside the case statement, redefining box as CustomControlTypeA, and even tried casting like so:

case "0":
    (CustomControlTypeA)box.richTextBox1.Rtf = str[5];
    break;

Solution

  • It's because you have a.Dispose(); & b.Dispose();. You're assinging one of them to box so it is also disposed.

    Oddly though, you're creating box as a new Control (which you don't need to do), but not disposing that.

    If you're adding a control to the .Controls collection you shouldn't be disposing it at all.

    This code should work though:

    foreach (string[] str in items)
    {
        Control box = null;
        switch (str[4])
        {
            case "0":
                CustomControlTypeA a = CustomControlTypeA();
                a.richTextBox1.Rtf = str[5];
                box = a;
                break;
    
            case "1":
                CustomControlTypeB b = new CustomControlTypeB();
                b.panel1.BackgroundImage = Image.FromFile(str[5]);
                box = b;
                break;
        }
        box.Location = new Point(x, y);
        box.Width = w;
        box.Height = h;
        panelBody.Controls.Add(box);
        box.BringToFront();
    }