As I read it, the problem here is that there is an inner loop, and there are things in Children that are not TextBlock s.
If LINQ is available:
foreach (TextBlock thisTextblock in thisGrid.Children.OfType<TextBlock>()) {
otherwise:
foreach (object child in thisGrid.Children) { TextBlock thisTextblock = child as TextBlock; if(thisTextblock == null) continue;
source share