Search code examples
c#wpfwpf-textbox

How can i use a Textbox, that was created programmatically?


I'm trying to write a four-in-a-row game in WPF.

I want to programmatically insert textboxes, which are my gameboxes. It works now, but I don't know how to control them with a button afterwards because I can't use the names I assign them.

The goal is to change the background color of the textboxes after pressing a button.

public MainWindow()
    {
        InitializeComponent();

        int x = 100;
        int y = 190;

        for (int i = 1; i < 43; i++)
        {
            TextBox tbx = new TextBox();

            tbx.Name = "Field" + i;

            tbx.Height = tbx.Width = 50;
            tbx.HorizontalAlignment = HorizontalAlignment.Left;
            tbx.VerticalAlignment = VerticalAlignment.Top;
            tbx.Margin = new Thickness(x, y, 0, 0);
            myGrid.Children.Add(tbx);

            x += 55;

            if (i % 7 == 0)
            {
                y += 55;
                x = 100;
            }

        }
    }

This is how it looks so far


Solution

  • Store the text boxes in a 2d array. Use a class field:

    private TextBox[,] textBoxes = new TextBox[7, 7];
    

    Integer division and modulo operations work best when numbering from 0 to N-1. If you started numbering i at 0, you could write

    x = 100 + (i % 7) * 55;
    y = 190 + i / 7 * 55;
    // and
    textBoxes[i % 7, i / 7] = tbx;
    

    Then you can access the textboxes with textBoxes[column, row] with both indexes ranging from 0 to 6.


    But you could simply use nested for loops instead of doing any index calculations

    for (int ix = 0; ix < 7; ix++) {
        for (int iy = 0; iy < 7; iy++) {
            int x = 100 + 55 * ix;
            int y = 190 + 55 * iy;
    
            var tbx = new TextBox();
            tbx.Height = tbx.Width = 50;
            tbx.HorizontalAlignment = HorizontalAlignment.Left;
            tbx.VerticalAlignment = VerticalAlignment.Top;
            tbx.Margin = new Thickness(x, y, 0, 0);
    
            myGrid.Children.Add(tbx);
            textBoxes[ix, iy] = tbx;
        }
    }