How to add rows and columns to a WPF Grid programmatically

By | February 1, 2013


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


Step:2 Give a name to the default Grid in the XAML markup


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


Write following in the Loaded event of Window1

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


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


Thanks for reading!

0 thoughts on “How to add rows and columns to a WPF Grid programmatically

  1. Johnb994

    I really like your writing style, fantastic information, thanks for putting up ekebdeeaeekb


Leave a Reply

Your email address will not be published. Required fields are marked *