Programmatically add label to grid
I corrected this by naming the other grid. I never had the grid named and therefore thats why the .Children.Add never would add to the grid. I tried mainGrid.Children.Add (mainGrid is the name of my parent grid) and it would always throw an error because it was the grid inside that it was needing for this part.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) //Handles Button1.Click
Dim dynamicLabel As new Label();
dynamicLabel.Name = "NewLabel";
dynamicLabel.Content = "TEST";
dynamicLabel.Width = 240;
dynamicLabel.Height = 30;
dynamicLabel.Margin = new Thickness(0, 21, 0, 0);
dynamicLabel.Foreground = new SolidColorBrush(Colors.White);
dynamicLabel.Background = new SolidColorBrush(Colors.Black);
Grid.SetRow(dynamicLabel, 0);
Grid.SetColumn(dynamicLabel, 0);
childGrid.Children.Add(dynamicLabel); //'<-changed to grid name in XAML properties
End Sub
If you need to add a button or a Label (just change Button to Label) to a Grid, you can use this:
internal void FillbtnSubCat(Grid grid)
{
var myDefinition = new ColumnDefinition();
var myButton = new Button();
Grid.SetColumn(myButton, count);
myButton.Margin = new Thickness(5, 10, 5, 25);
myButton.MinWidth = 30;
myButton.Content = count;
myButton.Click+= new RoutedEventHandler(Click1);
myDefinition.Width = new GridLength(68);
grid.ColumnDefinitions.Add(myDefinition);
grid.Children.Add(myButton);
count++;
}
void Click1(object sender, RoutedEventArgs e)
{
var myButton = sender as Button;
MessageBox.Show(myButton.GetHashCode().ToString());
}
and XAML
<ListView Grid.Column="0" Margin="10,10,5,5" Grid.Row="1" Grid.ColumnSpan="2">
<Grid Name="Grid1" Height="100" Width="auto">
</Grid>
</ListView>