0

I need to access a button in a for loop but it's Name has to be changed.

Ex:

  • There are a number of buttons whose Names are bt1,bt2,bt3,...bt25.
  • I'm using a for loop in my code for certain purpose to disable or enable those buttons.
  • Can I use a for loop to do this??

Like:

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

How cam I make the string as a control?

4 Answers 4

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

VB (using code converter):

For i As Integer = 1 To 24
    Me.Controls("bt" & i.ToString()).Enable = [True]
Next
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know VB syntax but by code conversion it become: For i As Integer = 1 To 24 Me.Controls("bt" & i.ToString()).Enable = [True] Next
1

You can do it in one line with LINQ

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

VB (also via converter)

Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False))

Comments

0

you can use following code :

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

if its inside any container control , then try this :

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

if want to implement in VB, then try this :

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

Comments

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
}

Above code is valid only if you really have 25 buttonns and named as bt1,bt2,bt3...,bt25

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

Above code is better if you want to enable all the buttons in a particular container (Form or panel etc).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.