Remove specified Children element of a Grid

22,054

Solution 1

If you keep a record of the control you can simply do:

grid1.Children.Remove(excontrol);

If you don't have a variable that holds the control you wish to remove you'll have to identify it in some way (Tag, Name), then find that control in the grid's children and then call Remove.

Solution 2

grid1.Children.Remove(excontrol) //edited per your edit -- this is exactly what ChrisF posted though

or

grid1.Children.RemoveAt(index)
Share:
22,054
Nicolò Carpignoli
Author by

Nicolò Carpignoli

Updated on March 26, 2020

Comments

  • Nicolò Carpignoli
    Nicolò Carpignoli about 4 years

    I need to remove at runtime a specified element of a Grid (grid1). This is the code where i add the elements.

     examControls.Add(excontrol);  // add the element on the ArrayList
     excontrol.Margin = new Thickness(x, y + margin, 0, 0);
     grid1.Children.Add(excontrol);   
    

    How can i remove at runtime a specified "excontrol" element (added at runtime) ?

    Thanks in advance

  • tnw
    tnw about 11 years
    @NicolòCarpignoli No problem. In the future, documentation is your friend. To find the answer to your question, I just googled "c# wpf grid". This pops up as the first result. You'll see Children is a UIElementCollection which shows you exactly what you're looking for.
  • Aric
    Aric almost 7 years
    does this free up memory space?
  • ChrisF
    ChrisF almost 7 years
    @AricFowler - I would assume so, once excontrol falls out of scope and isn't referenced anywhere else.
  • Carlos Rodriguez
    Carlos Rodriguez over 6 years
    And now when I google it, this answer pops up. So, ya know...thanks for asking lol