turtlepower
turtlepower

Reputation: 379

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.

Upvotes: 4

Views: 1250

Answers (4)

gmetax
gmetax

Reputation: 3973

If LINQ is available try that:

thisGrid.Children.OfType<TextBlock>().ToList().ForEach(tb =>
{
...your code here
});

Upvotes: 0

erikric
erikric

Reputation: 4169

foreach (var thisTextblock in thisGrid.Children)
                            {
                                 if(thisTextblock is Textblock)
                                     //Do Somthing
                            }

Upvotes: 0

Daren Thomas
Daren Thomas

Reputation: 70344

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>());

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1063704

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
}

Upvotes: 13

Related Questions