How To Remove All Children In HtmlElement With Silverlight/C#
So I have this Silverlight application that calls some reports(.rdlc) via HTML form submit. This form is universal, so I use it to call all reports with it. Now I want to clear the
Solution 1:
You should never add or remove elements while inside a foreach
loop, as the collection changes and invalidates the loop. Rather add all items to be removed in a separate list and then remove them in a second loop. (I haven't tested it because I do not have relevant sample code, but this is a common mistake with foreach
loops.)
List<HtmlElement> toRemove = new List<HtmlElement>();
foreach (HtmlElement element in Form.Children)
{
if (element.Id != string.Empty)
{
toRemove.Add(element);
}
}
foreach (HtmlElement element in toRemove)
{
Form.RemoveChild(element);
}
Alternatively, using your second approach, you can always add all your IDs to a list, and then add a RemoveAllFormInputs()
method which loops over these elements.
Solution 2:
Peet has provided the correct answer, however some may prefer a Linq based approach that slims the code a litte.
foreach (HtmlElement element in Form.Children
.OfType<HtmlElement>
.Where(e => !String.IsNullOrEmpty(e.Id))
.ToList() )
{
Form.RemoveChild(element);
}
Post a Comment for "How To Remove All Children In HtmlElement With Silverlight/C#"