locked
Creating and adding new button to each new row/column being created in a for loop in WPF C# RRS feed

  • Question

  • Hi, I am relatively new to WPF and im using Visual studio 2010.  The part that I am struggling with is;

    Based on the users selection to display either 2 or 3 rows along with 3, 4 or 5 columns, I want to draw this using a grid and add newly created event buttons to each row/column, for example if the user selects 2 rows with 3 columns then 6 buttons will appear on the screen, 3 along the top in the 1st row and 3 across the 2nd row.

    So far, using a for loop I can add the corresponding rows and columns that the user chooses and I can create a button;

    //add this stage i have already read in the  amount of rows and cols the user selects. Next step:

    for

     

     

    (int i = 0; i < row; i++)

    {

    diagramGroup.RowDefinitions.Add(

     

    new RowDefinition());  // adding row to the grid

     

     

    Button bt = new Button();  //creating new button an being added to each new row created

    bt.Name =

     

    "A" + i;

    bt.Height = 40;

    bt.Width = 60;

    bt.Margin =

     

    new Thickness(120, 20, 20, 20);

    bt.Content =

     

    "A" + i;

    bt.Click+=

     

    new RoutedEventHandler(bt_Click);

    diagramGroup.Children.Add(bt);

    bt.SetValue(

     

    Grid.RowProperty, +i); 

    }

     

     

    for (int j = 0; j < col; j++)

    {

    diagramGroup.ColumnDefinitions.Add(

     

    new ColumnDefinition());  //adds col to grid

     

     

    Button bt = new Button(); //adds new button to each new col created

    bt.Name =

     

    "B" + j;

    bt.Height = 40;

    bt.Width = 60;

    bt.Margin =

     

    new Thickness(120, 20, 20, 20);

    bt.Content =

     

    "B" + j;

    bt.Click +=

     

    new RoutedEventHandler(bt_Click);

    diagramGroup.Children.Add(bt);

    bt.SetValue(

     

    Grid.ColumnProperty, +j);

     }

    The problem is, that in the 'row' for-loop: it only displays the button in location '0' of each row.

    And in the 'Col' for-loop: it only displays the buttons in each col but only in the 1st row.  I attempted to put another forloop inside these to try an tell each other

    how many rows or cols each other has...but it give error.  Hope this isnt confusing.. 

    Is there another way I can achieve this?

    Appreciated, Emack

     

    Thursday, February 24, 2011 8:25 PM

Answers

All replies