如何从编程文本框获取值?

How to get values form programmatic text boxes?

我有以编程方式向面板添加新标签和文本框的代码:

 Label newLabel;
 TextBox newTextBox;
 int txtBoxStartPosition = 75;
 int txtBoxStartPositionV = 25;

   for (int i = 0; i<LB.SelectedItems.Count; i++)
        {
            newLabel = new Label();
            newTextBox = new TextBox();
            newTextBox.Location = new System.Drawing.Point(
                                  txtBoxStartPosition + 150,
                                  txtBoxStartPositionV);
            newTextBox.Size = new System.Drawing.Size(70, 40);
            newLabel.Location = new System.Drawing.Point(
                                txtBoxStartPosition, 
                                txtBoxStartPositionV);
            newLabel.Size = new System.Drawing.Size(120, 40);
            newTextBox.Text = "0";
            newLabel.Text = LB.SelectedItems[i].ToString();
            this.panel1.Controls.Add(newTextBox);
            this.panel1.Controls.Add(newLabel);
            txtBoxStartPositionV += 50;
        }   

在 运行 之后...用户将在文本框中输入值,然后单击 "ok" 按钮。 如何在 void button1_Click(object sender, EventArgs e) 函数中获取这些值????

由于您要将所有 TextBox 添加到 panel1,您可以像这样访问它们:

var allTextBoxesInPanel1 = panel1.Controls.OfType<TextBox>();

然后您可以迭代结果并获取每个 TextBox 的值。

foreach(TextBox textBox in allTextBoxesInPanel1)
{
    Console.WriteLine(textBox.Text);
}