Marcelo Camargo
Marcelo Camargo

Reputation: 2298

C# Remove Component By Name

Well, I'm creating a method able to remove a component from a panel according to its name and its type. My code is currently:

private void RemoveItemByName<T>(Panel panel, string name)
{
    foreach (T item in panel.Controls.OfType<T>().Where(item => item.Name == name))
        panel.Controls.Remove(item);
}

But the property Name doesn't exist in type T because T didn't be defined yet. I want to use it this way:

RemoveItemByName<TextBox>(pnlMain, "txtPesquisa");
RemoveItemByName<Button>(pnlMain, "btnCloseSearch");

In this case, the compiler gives me two errors: Cannot resolve symbol 'Name' in item and Argument type 'T' is not assignable to parameter type 'System.Windows.Forms.Control'

When I try to cast T to the accepted type it doesn't allow me to do. How can I do this conversion in way that this work in this way?

Upvotes: 0

Views: 441

Answers (1)

Arian Motamedi
Arian Motamedi

Reputation: 7413

You'd have to give T a constraint so the compiler knows what methods and properties are available on the type:

private void RemoveItemByName<T>(Panel panel, string name) 
  where T : System.Windows.Control
{
    foreach (T item in panel.Controls.OfType<T>().ToList().Where(
     item => item.Name == name))
          panel.Controls.Remove(item);
}

This will tell the compiler any object of type Control (including objects that inherit from it) can be passed in to the method.

Upvotes: 1

Related Questions