❔ System.InvalidCast Exception when looping through Controls.Grid.Children

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.Button' to type 'System.Windows.Controls.UIElementCollection'.' trying to programatically add buttons to a grid, but I'm getting this error when looping through the grids children. this is where I'm looping through it
private void addGameToView(Game game)
{
Button button = new Button();
if (game.Icon == null)
{
button.Content = game.Name;

if (gamesGrid.Children.Count > 0) {
foreach (UIElementCollection child in gamesGrid.Children) //ERROR HERE
{
foreach (UIElement element in child)
{
Debug.Write(element.ToString());
if (child.GetType() != typeof(Game))
{
//Grid.SetColumn(button, Grid.GetColumn(element));
//Grid.SetRow(button, Grid.GetRow(element));
//gamesGrid.Children.Add(button);
//break;
}
}
}
} else
{
Grid.SetColumn(button, 0);
Grid.SetRow(button, 0);
gamesGrid.Children.Add(button);
}
}
}
private void addGameToView(Game game)
{
Button button = new Button();
if (game.Icon == null)
{
button.Content = game.Name;

if (gamesGrid.Children.Count > 0) {
foreach (UIElementCollection child in gamesGrid.Children) //ERROR HERE
{
foreach (UIElement element in child)
{
Debug.Write(element.ToString());
if (child.GetType() != typeof(Game))
{
//Grid.SetColumn(button, Grid.GetColumn(element));
//Grid.SetRow(button, Grid.GetRow(element));
//gamesGrid.Children.Add(button);
//break;
}
}
}
} else
{
Grid.SetColumn(button, 0);
Grid.SetRow(button, 0);
gamesGrid.Children.Add(button);
}
}
}
this is the XAML defining the rows & columns
<Grid Name="gamesGrid" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
<Grid Name="gamesGrid" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
2 Replies
Dawwa | Слава Украине
heres a gist with where I'm calling the function as well https://gist.github.com/Dawwa1/7dc1880282572486b0bbf79aa0b26219
Gist
System.InvalidCast Exception when looping through Controls.Grid.Chi...
System.InvalidCast Exception when looping through Controls.Grid.Children - MainWindow.xaml.cs
Accord
Accord8mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.