2010-10-27 101 views
1

是否有一種簡單的方法從我的表單上的現有按鈕創建按鈕集合? (在C#中)。從現有按鈕創建按鈕陣列(集合)

我有一系列已經在我的表格按鈕,我想使用索引來訪問它們...例如: -

myButtonArray[0].ForeColor ...// Do something with it 

可以這樣做?

編輯:我可以設置數組有一個通用的OnClick事件嗎?然後確定數組中的哪個按鈕被點擊,並且改變它的顏色?

回答

1

您可以按照與其他任何陣列相同的方式進行操作。例如:

Button[] array = { firstButton, secondButton }; 

,或者如果你需要在一個地方申報,後來分配:

Button[] array; 
... 
array = new Button[] { firstButton, secondButton }; 

在C#3+可以使用隱式類型的數組的初始化:

Button[] array; 
... 
array = new[] { firstButton, secondButton }; 

您可能還想考慮使用List<Button>代替:

List<Button> buttons = new List<Button> { firstButton, secondButton }; 
1

類似:

var myButtonArray = new[] {btn1, btn2, btn3, btn4}; 
6

LINQ救援!

Button[] buttons = this.Controls.OfType<Button>().ToArray(); 
+0

在另一方面,你那麼不知道哪個是哪個。它也不會找到在面板等按鈕。 – 2010-10-27 21:08:05

+0

好我喜歡它。 – 2010-10-27 21:08:59

+0

這當然是一個好點。幸運的是,我的要求並沒有說面板內有按鈕。 :) – Bryan 2010-10-27 21:09:48

0

假設有一個命名約定...

List<Button> asdf = new List<Button>(); 
for (int x = 0; x <= 10; x++) { 
    asdf.Add(myButton + x); 
} 
3
var myButtonArray = new [] {this.Button1, this.Button2, ...} 

。如果有很多按鈕的簡化這一過程,你可以嘗試在形式的層面驗證碼:

this.Controls.OfType<Button>().ToArray(); 

您可以使用具有非空控件集合本身的控件集合中的任何控件進行遞歸。

0

您在表單的Controls屬性中擁有所有控件,因此必須迭代該集合並將其添加到數組中。

List<Button> buttons = new List<Button>(); 

foreach(Control c in this.Controls) 
{ 
    Button b = c as Button; 
    if(b != null) 
    { 
     buttons.Add(b); 
    } 
} 
0

In response to your requirements(Edit: Can I set the array to have a generic OnClick event? And then determine which button in the array was clicked and, say, change its color?)

List<Button> buttons = new List<Button> { firstButton, secondButton }; 

// Iterate through the collection of Controls, or you can use your List of buttons above. 
foreach (Control button in this.Controls) 
{ 
    if (button.GetType() == typeof(Button)) // Check if the control is a Button. 
    { 
     Button btn = (Button)button; // Cast the control to Button. 
     btn.Click += new System.EventHandler(this.button_Click); // Add event to button. 
    } 
} 

// Click event for all Buttons control. 
private void button_Click(Button sender, EventArgs e) 
{ 
    ChangeForeColor(sender); // A method that accepts a Button 
    // other methods to do... 
    // you can also check here what button is being clicked 
    // and what action to do for that particular button. 
    // Ex: 
    // 
    // switch(sender.Name) 
    // { 
    //  case "firstButton": 
    //   sender.ForeColor = Color.Blue; 
    //   break; 
    //  case "secondButton ": 
    //   sender.Text = "I'm Button 2"; 
    //   break; 
    // } 
} 

// Changes the ForeColor of the Button being passed. 
private void ChangeForeColor(Button btn) 
{ 
    btn.ForeColor = Color.Red; 
}