我有多种方法的程序。 我们使用方法创建所有控件。 其中一种方法是创建textBox。它就像:
private TextBox textBox1;
public void CreateTextBox()
{
this.textBox1 = new System.Windows.Forms.TextBox();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(100, Position);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
Position += 30;
this.Controls.Add(this.textBox1);
}
表单中有多个textBox(文本框的计数可能会在10到20之间变化)。 所以,如果我想创建几个textBox,请调用方法,如:
CreateTextBox();
CreateTextBox();
CreateTextBox();
如果我想要这个文本框的文本,像这样的代码返回最后一个textBox文本:
MessageBox.Show(textBox1.Text);
我的问题是,,,,如何检测第一次调用CreateTextBox()和第二次调用CreateTextBox()的文本? 谢谢你的阅读
答案 0 :(得分:1)
您可以使用包含所有TextBoxes
的数组:
var form = new Form();
var boxes = new TextBox[10];
for (int i = 0; i < boxes.Length; i++)
{
var box = new TextBox();
box.Location = new Point(10, 30 + 25 * i);
box.Size = new Size(100, 20);
form.Controls.Add(box);
boxes[i] = box;
}
var button = new Button();
button.Text = "Button";
button.Click += (o, e) =>
{
var message = String.Join(", ", boxes.Select(tb => tb.Text));
MessageBox.Show(message);
};
form.Controls.Add(button);
Application.Run(form);