2012-09-14 59 views
0

我有一個Form有兩個控件,ButtonTextBox
這些控件是在運行時創建的。如何處理在運行時創建的Windows窗體控件?

當我點擊Button時,我想用TextBox.Text屬性做一些操作。
但是,與此代碼我不能:

private void Form1_Load(object sender, EventArgs e) 
{ 
    TextBox txb = new TextBox(); 
    this.Controls.Add(txb); 
    Button btn = new Button(); 
    this.Controls.Add(btn); 
    btn.Click += new EventHandler(btn_Click); 
} 

在這裏,我試圖找到它:

public void btn_Click(object sender, EventArgs e) 
{ 
    foreach (var item in this.Controls) 
    { 
     if (item is TextBox) 
     { 
      if (((TextBox)item).Name=="txb") 
      { 
       MessageBox.Show("xxx"); 
      } 
     } 
    } 
} 

回答

0

您沒有名稱爲「TXB」一個文本框。所以,這個表達式永遠是假的:if(((TextBox)item).Name=="txb")

試試這個代碼:

private void Form1_Load(object sender, EventArgs e) 
{ 
    TextBox txb = new TextBox(); 
    txb.Name = "txb"; 
    this.Controls.Add(txb); 
    Button btn = new Button(); 
    this.Controls.Add(btn); 
    btn.Click += new EventHandler(btn_Click); 
} 
0

我會參考保存給您的TextBox

TextBox txb; 
private void Form1_Load(object sender, EventArgs e) 
{ 
    txb = new TextBox(); 
    this.Controls.Add(txb); 
    Button btn = new Button(); 
    this.Controls.Add(btn); 
    btn.Click += new EventHandler(btn_Click); 
} 
相關問題