Krishna Thota Krishna Thota - 3 months ago 5
C# Question

How to access a button using its name as a string in a for loop

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?

Answer
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
Comments