0

我需要在 for 循环中访问一个按钮,但它的名称必须更改。

前任:

  • 有许多按钮的名称是 bt1,bt2,bt3,...bt25。
  • 我在我的代码中使用 for 循环来禁用或启用这些按钮。
  • 我可以使用 for 循环来执行此操作吗?

喜欢:

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

我如何将字符串作为控件?

4

4 回答 4

8
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
于 2012-10-19T07:36:26.783 回答
1

您可以使用 LINQ 在一行中完成

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

VB(也通过转换器)

Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False))
于 2012-10-19T07:58:01.643 回答
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
于 2012-10-19T07:49:30.773 回答
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;
            }
        }

如果您想启用特定容器(表单或面板等)中的所有按钮,上面的代码会更好。

于 2012-10-19T08:01:48.490 回答