2012-10-19 17 views
0

我需要訪問for循環中的按鈕,但它的名稱必須更改。如何在for循環中使用其名稱作爲字符串訪問按鈕

例:

  • 有許多按鈕,其名稱是BT1,BT2,BT3,... BT25的。
  • 我在代碼中使用了for循環來實現某些目的來禁用或啓用這些按鈕。
  • 我可以使用for循環來做到這一點?

像:

for(int i =1;i<25;i++) 
{ 
    "bt"+"i".Enable = True; 
} 

如何凸輪我做字符串作爲控制?

回答

7
for(int i =1;i<25;i++) 
{ 
    this.Controls["bt"+ i.ToString()].Enable = True; 
} 

VB(使用代碼轉換器):

For i As Integer = 1 To 24 
    Me.Controls("bt" & i.ToString()).Enable = [True] 
Next 
+0

我們如何在VB中做到這一點? –

+0

我不知道VB的語法,但通過代碼轉換它變成:For i As Integer = 1 To 24 \t Me.Controls(「bt」&i.ToString())。Enable = [True] Next –

0

你可以用下面的代碼:

foreach (Control ctrl in this.Controls) 
      { 
       if (ctrl is Button) 
       { 
        ctrl.Enabled = true; 
       } 
      } 

如果任何容器控件內,那就試試這個:

foreach (Control Cntrl in this.Pnl.Controls) 
      { 
       if (Cntrl is Panel) 
       { 
        foreach (Control C in Cntrl.Controls) 
         if (C is Button) 
         { 
          C.Enabled = true; 
         } 
       } 
      } 

如果想在VB中實現,那麼試試t他:

For Each Cntrl As Control In Me.Pnl.Controls 
    If TypeOf Cntrl Is Panel Then 
     For Each C As Control In Cntrl.Controls 
      If TypeOf C Is Button Then 
       C.Enabled = False 
      End If 
     Next 
    End If 
Next 
1

你能做到在一個符合LINQ

Controls.OfType<Button>().ToList().ForEach(b => b.Enabled = false); 

VB(也可以通過轉換器)

Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False)) 
1
for(int i =1;i<=25;i++) 
{ 
    this.Controls["bt"+ i].Enable = True; 
//Or 
    //yourButtonContainerObject.Controls["bt"+ i].Enable = True; 
    // yourButtonContainerObject may be panel1, pane2 or Form, Depends where 
    // your buttons are added. 'this' can be used in case of 'Form' only 
} 

上面的代碼纔有效,如果你真的有25鈕釦,命名爲bt1,bt2,bt3 ...,bt25

 foreach (Control ctrl in yourButtonContainerObject.Controls) 
     { 
      if (ctrl is Button) 
      { 
       ctrl.Enabled = false; 
      } 
     } 

如果要啓用特定容器(窗體或面板等)中的所有按鈕,上面的代碼更好。

相關問題