Introduction
In this post we will see how to add rows and columns to a Grid in WPF programmatically using code behind. After adding rows and columns to the Grid, we will add some Buttons to it. We will set background of these buttons to random colors using RandomColor class created in my last article
Step:1 Create a new WPF Application
Image may be NSFW.
Clik here to view.
Step:2 Give a name to the default Grid in the XAML markup
Image may be NSFW.
Clik here to view.
Step:3
Import System.Reflection in the code behind (Window1.xaml.cs) and add reference to System.Drawing so that we can access System.Drawing.Color in our RandomColor class. And add code of RandomClass in the same namespace
Image may be NSFW.
Clik here to view.
Step:4
Write following in the Loaded event of Window1
Image may be NSFW.
Clik here to view.
ColumnDefinitions.Add and RowDefinitions.Add methods of Grid are used to add a column and a row respectively. A for loop is used to add controls (a Button) in each cell of the Grid. Button is initialized in each loop and its properties are set. Its background color is set using RandomColor class. SetValue method of button is used to specify row and column of the button in the Grid and finally Children.Add method of the Grid is used to add button to the Grid
Conclusion
We have added two rows and two columns to the Grid and we have added a Button control in each cell with a random background color
Image may be NSFW.
Clik here to view.
Thanks for reading!
Filed under: .Net, WPF Image may be NSFW.
Clik here to view.
