StealthRT StealthRT - 7 months ago 30
Vb.net Question

Programmatically add label to grid

Hey all i am trying to add a label to my grid using the following code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim dynamicLabel As New Label()
Dim g As New Grid

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, 6)
g.Children.Add(dynamicLabel)
End Sub


However, i never see anything on the grid after i push the button... what am i missing?

Answer

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