Dynamically create multiple C # text fields

This is my code. But all my textboxes are null.

    public void createTxtTeamNames()
    {
        TextBox[] txtTeamNames = new TextBox[teams];
        int i = 0;
        foreach (TextBox txt in txtTeamNames)
        {
            string name = "TeamNumber" + i.ToString();
            txt.Name = name;
            txt.Text = name;
            txt.Location = new Point(172, 32 + (i * 28));
            txt.Visible = true;
            i++;
        }
    }

Thanks for the help.

+2
source share
5 answers

An array creation request initializes elements only null. You need to create them individually.

TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
  var txt = new TextBox();
  txtTeamNames[i] = txt;
  txt.Name = name;
  txt.Text = name;
  txt.Location = new Point(172, 32 + (i * 28));
  txt.Visible = true;
}

Note. As pointed out by several people, for this code to make sense, you need to add each TextBoxto the parentControl

+9
source

You need to initialize your text box at the beginning of the loop.

You also need to use a for loop instead of foreach.

+1
source

:

for (int i = 0; i < teams; i++)
{
    txtTeamNames[i] = new TextBox();
    ...
}
+1

, , . .

public void createTxtTeamNames()
        {
            TextBox[] txtTeamNames = new TextBox[10];

for (int u = 0; u < txtTeamNames.Count(); u++)
            {
                txtTeamNames[u] = new TextBox();
            }
            int i = 0;
            foreach (TextBox txt in txtTeamNames)
            {
                string name = "TeamNumber" + i.ToString();

                txt.Name = name;
                txt.Text = name;
                txt.Location = new Point(0, 32 + (i * 28));
                txt.Visible = true;
                this.Controls.Add(txt);
                i++;
            }
        }
0
source
    private void button2_Click(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        tb.Name = abc;
        tb.Text = "" + i;

        Point p = new Point(20 + i, 30 * i);
        tb.Location = p;
        this.Controls.Add(tb);
        i++;
    }


    private void button3_Click(object sender, EventArgs e)
    {
        foreach (TextBox item in this.Controls.OfType<TextBox>())
        {
            MessageBox.Show(item.Name + ": " + item.Text + "\\n");   
        }
    }
0
source

Source: https://habr.com/ru/post/1525831/


All Articles