Mega Code Archive

 
Categories / C# Tutorial / WPF
 

Add controls to a Grid with loop

using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; public class EnterTheGrid : Window {     [STAThread]     public static void Main()     {         Application app = new Application();         app.Run(new EnterTheGrid());     }     public EnterTheGrid()     {         MinWidth = 300;         SizeToContent = SizeToContent.WidthAndHeight;         StackPanel stack = new StackPanel();         Content = stack;         Grid grid1 = new Grid();         grid1.Margin = new Thickness(5);         stack.Children.Add(grid1);         for (int i = 0; i < 5; i++)         {             RowDefinition rowdef = new RowDefinition();             rowdef.Height = GridLength.Auto;             grid1.RowDefinitions.Add(rowdef);         }         ColumnDefinition coldef = new ColumnDefinition();         coldef.Width = GridLength.Auto;         grid1.ColumnDefinitions.Add(coldef);         coldef = new ColumnDefinition();         coldef.Width = new GridLength(100, GridUnitType.Star);         grid1.ColumnDefinitions.Add(coldef);         string[] strLabels = { "_A:", "_B:" };         for (int i = 0; i < strLabels.Length; i++)         {             Label lbl = new Label();             lbl.Content = strLabels[i];             lbl.VerticalContentAlignment = VerticalAlignment.Center;             grid1.Children.Add(lbl);             Grid.SetRow(lbl, i);             Grid.SetColumn(lbl, 0);             TextBox txtbox = new TextBox();             txtbox.Margin = new Thickness(5);             grid1.Children.Add(txtbox);             Grid.SetRow(txtbox, i);             Grid.SetColumn(txtbox, 0);         }         (stack.Children[0] as Panel).Children[1].Focus();     } }