1

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);
        }

1 Answer 1

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.