我需要访问for循环中的按钮,但是必须更改名称。
例如:
像:
for(int i =1;i<25;i++)
{
"bt"+"i".Enable = True;
}
我如何将字符串作为控件?
答案 0 :(得分: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
答案 1 :(得分:1)
您可以使用LINQ
在一行中完成Controls.OfType<Button>().ToList().ForEach(b => b.Enabled = false);
VB(也通过转换器)
Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False))
答案 2 :(得分: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中实现,那么试试这个:
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
答案 3 :(得分:0)
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;
}
}
如果要启用特定容器(表单或面板等)中的所有按钮,上面的代码会更好。