Kirsten
Kirsten

Reputation: 18198

argument type 'object' is not assignable to parameter type 'System.Windows.Forms.Control

I am trying to remove a drawing from my winform. What is wrong with my code?

  private void removeDrawing()
    {
        foreach (var ctrl in this.Controls)
        {
          if (ctrl.GetType().ToString() == "Microsoft.VisualBasic.PowerPacks.ShapeContainer")
            {
                this.Controls.Remove(ctrl); // argument type 'object' is not assignable to parameter type 'System.Windows.Forms.Control
            }
        }
    }

[Update] Thanks for the answer. I implemented it as

while (this.Controls.OfType<ShapeContainer>().Any())
        {
            var ctrl = this.Controls.OfType<ShapeContainer>().First();
            this.Controls.Remove(ctrl);
        }

Upvotes: 1

Views: 5794

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149108

You'll still have to cast ctrl to the correct type, but I wouldn't recommend doing type checking by name. Try this instead:

private void removeDrawing()
{
    foreach (var ctrl in this.Controls)
    {
        var shapeContainer = ctrl as ShapeContainer;
        if (shapeContainer != null)
        {
            this.Controls.Remove(shapeContainer);
        }
    }
}

However, a little Linq can help you out here. See the OfType extension method:

using System.Linq;
...

private void removeDrawing()
{
    foreach (var ctrl in this.Controls.OfType<ShapeContainer>().ToList())
    {
        this.Controls.Remove(ctrl);
    }
}

Upvotes: 6

Related Questions