2016-05-30 64 views
-3
private void clearBoard() 
{ 
    button1.Text = null; 
    button2.Text = null; 
    button3.Text = null; 
    button4.Text = null; 
    button5.Text = null; 
    button6.Text = null; 
    button7.Text = null; 
    button8.Text = null; 
    button9.Text = null; 
} 

我有9個按鈕。 (button1 - button9)。我希望他們全部清除文字。 有沒有更有效的方法來做到這一點,而不是通常清除每一個?是否有影響形式上出現的幾個按鈕的快捷方式?

順便說一句,我知道我可以創建按鈕的數組,但在這裏,所有按鈕手動從窗口創建。所以也許在這裏是不可能的。

+0

WinForms?的WebForms? ASP.NET MVC? WPF? –

+1

我更喜歡製作我自己的按鈕列表。搜索窗體控件速度很慢。試試這個:列表

回答

3

我可以想出的唯一增強功能是將按鈕放入列表或數組中。如果你手動創建你的按鈕,一個方法是在你的表格來聲明一個成員變量:

public partial class Form1 : Form 
{ 
    private List<Button> buttons = new List<Button>(); 

    //... 
} 

並添加按鈕到列表,當你創建它們:

private void CreateNextButton() 
{ 
    Button button = new Button(); 
    // initialize button 
    Controls.Add(button); 

    // add button to your list 
    buttons.Add(button); 
} 

然後改變你的clearBoard到:

private void clearBoard() 
{ 
    foreach(Button button in buttons) button.Text = string.Empty; 
} 
1

我認爲更簡單的形式是循環在頁面的控件,並設置按鈕的文本屬性只。

protected void Page_Load(object sender, EventArgs e) 
{ 
    foreach (Control control in Page.Controls) 
    { 
     if (control is Button) 
     { 
      ((Button)control).Text = string.Empty; 
     } 
    } 
} 

不要忘記,你應該循環遍歷按鈕分層的父控件。如果他們是一個div裏面,遍歷該分區(說這是id爲myDiv) - 這樣的:

foreach(Control control in myDiv.Controls) 
0

您可以通過控制環和檢查它是否是一個Button,如果是這樣,Text屬性設置爲null

foreach (var button in this.Controls) 
{ 
    if (button is Button) 
    { 
     ((Button)button).Text = null; 
    } 
} 
5

如果要清除文本表格所有的按鈕,使用此:

foreach (Control b in this.Controls.OfType<Button>()) 
     b.Text = string.Empty; 

但是,如果你想爲只有9 Butto明文NS,有各種方法,其中有兩個如下:

for (int i = 1; i <= 9; i++) 
{ 
    var button = this.Controls.OfType<Button>().Where(b => b.Name == "button" + i).FirstOrDefault(); 
    if (button != null) button.Text = string.Empty; 
} 

或者你也可以使用這個:

List<Button> listButtons = new List<Button>() { button1, button2, button3, 
    button4, button5, button6, button7, button8, button9 }; 
foreach (var item in listButtons) 
    item.Text = string.Empty; 
+0

如果他的表單上還有其他按鈕,該怎麼辦? –

+1

OP從來沒有表明他想清除'Form'上的_all_按鈕,但只有這些具體的9.如果沒有更多的按鈕,我寧願你的答案。 –

+0

謝謝,如果我將添加其他按鈕,它會導致問題。是不是像這樣的其他方法?:int i = 0,For(......){button {0} .text = null;我++;} ???? –

0

如果他們是在窗口本身,你可以做

private void ClearButton() 
{ 
    foreach (var control in this.Controls) 
    { 
     Button btn = control as Button; 
     if (btn != null) 
     { 
      btn.Text = string.Empty; 
     } 
    } 
} 
相關問題