2013-05-18 137 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 }); 
     } 
    } 
}