我需要访问for循环中的按钮,但它的名称必须更改。如何在for循环中使用其名称作为字符串访问按钮
例:
- 有许多按钮,其名称是BT1,BT2,BT3,... BT25的。
- 我在代码中使用了for循环来实现某些目的来禁用或启用这些按钮。
- 我可以使用for循环来做到这一点?
像:
for(int i =1;i<25;i++)
{
"bt"+"i".Enable = True;
}
如何凸轮我做字符串作为控制?
我需要访问for循环中的按钮,但它的名称必须更改。如何在for循环中使用其名称作为字符串访问按钮
例:
像:
for(int i =1;i<25;i++)
{
"bt"+"i".Enable = True;
}
如何凸轮我做字符串作为控制?
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
你可以用下面的代码:
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
你能做到在一个符合LINQ
Controls.OfType<Button>().ToList().ForEach(b => b.Enabled = false);
VB(也可以通过转换器)
Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False))
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;
}
}
如果要启用特定容器(窗体或面板等)中的所有按钮,上面的代码更好。
我们如何在VB中做到这一点? –
我不知道VB的语法,但通过代码转换它变成:For i As Integer = 1 To 24 \t Me.Controls(“bt”&i.ToString())。Enable = [True] Next –