2015-09-26 67 views
0

此功能動態創建九個按鈕,供我在製作的遊戲中使用。你可以看到我給這個按鈕的屬性。引用一個循環外的按鈕?

private void createbuttons() 
{ 
    int tot = 0; 
    int x = 100; 
    int y = 100; 

    while(tot < 9) 
    { 
     string buttonsname = (tot + "button").ToString(); 
     Button creating = new Button(); 
     creating.Name = buttonsname; 
     creating.Size = new Size(100, 100); 
     creating.Click += delegate 
     { 
      MessageBox.Show("You clicked me!"); 
     }; 
     creating.Text = buttonsname; 
     if(x > 300) 
     { 
      y += 100; 
      x = 100; 

     } 
     creating.Location = new Point(x, y); 

     Controls.Add(creating); 
     tot += 1; 
     x += 100; 
    } 

} 

我想知道的是如何在同一個窗體的不同部分引用這些按鈕。特別是當單擊「開始遊戲」時,我想將每個按鈕的文本更改爲不同的內容。

private void button10_Click(object sender, EventArgs e) 
{ 
    //What would I write here to change the text? 
} 

回答

0

該表格有一個屬性Controls,其中包含所有子控件。通過其Name屬性使用方法Find找到一個子控件,它返回數組,因爲可能有幾個控件使用相同的Name,但是如果確保名稱存在,是唯一的,並且您知道它們的類型(Button),您可以只從陣列採取的第一個項目,並投它:

private void button10_Click(object sender, EventArgs e) 
{ 
    Button buttonNamedFred = (Button)this.Controls.Find("Fred", false)[0]; 

    buttonNamedFred.Text = "I'm Fred"; 
} 
2

您可以通過枚舉訪問控制的按鈕,或者你可以創建以供將來參考按鈕的列表,並在以後使用該列表。

這裏是你如何與清單做:

private IList<Button> addedButtons = new List<Button>(); 
private void createbuttons() { 
    int tot = 0; 
    int x = 100; 
    int y = 100; 

    while(tot < 9) { 
     string buttonsname = (tot + "button").ToString(); 
     Button creating = new Button(); 
     creating.Name = buttonsname; 
     creating.Size = new Size(100, 100); 
     creating.Click += delegate { 
      MessageBox.Show("You clicked me!"); 
     }; 
     creating.Text = buttonsname; 
     if(x > 300) { 
      y += 100; 
      x = 100; 
     } 
     creating.Location = new Point(x, y); 
     addedButtons.Add(creating); // Save the button for future reference 
     Controls.Add(creating); 
     tot += 1; 
     x += 100; 
    } 
} 

現在你可以這樣做:

foreach (var btn : addedButtons) { 
    btn.Text = "Changed "+btn.Text; 
} 
+0

謝謝,我想我可能需要添加列表:) – Robjames970

+0

的列表(實際上是一個ControlCollection)已經存在。無需維護另一個。 – Dialecticus

+0

@Dialecticus在'Controls'集合之外保持按鈕和其他控件位於不同的集合中可以節省大型表單的CPU週期,並且還可以提高代碼的可讀性。 – dasblinkenlight