2013-05-18 136 views
0

文本我有一个按钮,点击后动态创建文本框:获取从动态创建文本框

 for (int i = 0; i < length; i++) 
     { 
     Name.Add(new TextBox()); 
     System.Drawing.Point locate = new System.Drawing.Point(137, 158 + i * 25); 
     (Name[i] as TextBox).Location = locate; 
     (Name[i] as TextBox).Size = new System.Drawing.Size(156, 20); 
     StartTab.Controls.Add(Name[i] as TextBox); 
     } 

我想在名称中输入的文本[我]转换为字符串,然后将其设置为标签

+0

你想什么时候做?在显示的代码中,控件甚至还没有显示给用户,所以用户不能输入任何内容。 – Guffa

+0

@ newStackExchangeInstance modname [i] = Name [i] .ToString(); string assessName = modname [i]; – yeeeh

+0

“modname”的声明类型是什么?您需要访问TextBoxes的.Text()属性,例如'(Name [i] TextBox).Text'。你可以试试:'(modname [i]为Label).Text =(Name [i] as TextBox).Text' –

回答

3

您可以使用Control.ControlCollection.Find

更新:

TextBox txtName = (TextBox)this.Controls.Find("txtNameOfTextbox", true)[0]; 

if (txtName != null) 
{ 
    return txtName.Text; 
} 
+0

它说'不包含FindControl的定义' – yeeeh

+0

-1它是** winform ** apllication。 – I4V

+0

你是对@ I4V,感谢您的警告。更新了我的答案。你可以试试吗? –

0

你不说Name是,它看起来什么类型的像某种形式的名单。尝试使用List<TextBox>,您可以直接访问TextBox属性。像这样的东西。我也不确定StartTab是什么控制,所以我只用了Panel这个测试代码。 (你也应该知道,Name掩盖了窗体的Name财产,这就是为什么我改变了你的列表name

public partial class Form1 : Form 
{ 
    List<TextBox> name = new List<TextBox>(); 
    int length = 5; 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < length; i++) 
     { 
      name.Add(new TextBox() { Location = new System.Drawing.Point(137, 158 + i * 25), 
            Size = new System.Drawing.Size(156, 20) }); 
      StartTab.Controls.Add(name[i]); 
     } 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < length; i++) 
     { 
      StartTab.Controls.Add(new Label() {Location = new System.Drawing.Point(name[i].Location.X + name[i].Width + 20, 
               name[i].Location.Y), 
               Text = name[i].Text, 
               AutoSize = true }); 
     } 
    } 
}