Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Foreach Item In

I have a Listbox, which houses some items. The Items are Grids which house a variety of Textblocks, buttons, etc etc.

foreach (Grid thisGrid in myListBox.SelectedItems)
                        {
                                foreach (TextBlock thisTextblock in thisGrid.Children)
                                {
                                     //Do Somthing
                                }
                        }

Yet this throws an exception because there are other items than Textblock's in there. How can I accomodate this? Thanks.

like image 984
turtlepower Avatar asked Dec 05 '22 00:12

turtlepower


2 Answers

As I read it, the problem here is with the inner loop, and there being things in Children that are not TextBlocks.

If LINQ is available:

foreach (TextBlock thisTextblock in thisGrid.Children.OfType<TextBlock>()) {
    // ... do something here
}

otherwise:

foreach (object child in thisGrid.Children) {
    TextBlock thisTextblock = child as TextBlock;
    if(thisTextblock  == null) continue;
    // ... do something here
}
like image 148
Marc Gravell Avatar answered Dec 14 '22 10:12

Marc Gravell


you could try

foreach (TextBlock thisTextblock in thisGrid.Children.Where(c => c is TextBlock))
{ /* ... */ }

for your inner loop.

EDIT: TIL, that this can also be written as:

foreach (TextBlock in thisTextblock in thisGrid.Children.OfType<TextBlock>());
like image 28
Daren Thomas Avatar answered Dec 14 '22 11:12

Daren Thomas