Search code examples
wpffor-looptextboxstackpanel

How to bind values Programatically created Textbox in a for loop


The Stack panels and Textbox are programmatically in a for-loop, by just changing the margins. Then these are inturn added to the Window context.

Now, When the user enters the values in the TextBox, I need to bind them to seperate fields. But, for some reason, the Textbox is not enabled and I think the reason is the fields are not binded properly.

            StackPanel panel1 = new StackPanel();

            for (int i = 0; i < 10; i++)
            {

                TextBox txtProgramValue1 = new TextBox();
                txtProgramValue1.FontSize = 14;
                txtProgramValue1.Height = 32;
                txtProgramValue1.HorizontalAlignment = HorizontalAlignment.Right;
                txtProgramValue1.VerticalAlignment = VerticalAlignment.Top;
                txtProgramValue1.Width = 126;
                txtProgramValue1.Margin = new Thickness(0, 51 + (i * 100), 16, 0);
                txtProgramValue1.Name = "lblProgramValue" + i.ToString();
                txtProgramValue1.IsEnabled = true;

                panel1.Children.Add(txtProgramValue1);
            }

I need to map the txtProgramValue1.Text of each TextBox to a list.


Solution

  • The use of Textbox as an array

    Textbox[] _Textbox = new Textbox[5];
    for(int i=0; i < 5;i++)
    {
    _Textbox[i] = new Textbox();
    }
    

    This solves this question.