2014-09-06 79 views
-1

我有多种方法的程序。 我们使用方法创建所有控件。 其中一种方法是创建文本框。它是这样的:检测多文本框的文本

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); 

    } 

有一个形成若干个文本框(文本框的次数可能到20 10之间变化)。 所以,如果我想创建多个文本框,调用的方法,如:

 CreateTextBox(); 
     CreateTextBox(); 
     CreateTextBox(); 

如果我想有这个文本框的文本,像这样的代码返回我的最后textBox中文字:

  MessageBox.Show(textBox1.Text); 

我的问题是,,,,如何检测第一次调用CreateTextBox()和第二次调用CreateTextBox()的文本? 感谢ü为读

+0

使您的代码返回一个文本框,并将它们存储在列表中。 – 2014-09-06 19:01:24

+0

或者只是给他们不同的名字。 – 2014-09-06 19:01:44

+0

或者使用'Tag'并循环它们...无论什么最有意义... – walther 2014-09-06 19:03:47

回答

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); 
+0

是的...这是对的 。谢谢<3 – Sinaw 2014-09-06 19:13:48