1

In visual c#, I have built a win form in which I have 10 buttons I have the following code for button10_Click(object sender, EventArgs e):

button1.Text = "A".toString();
button2.Text = "B".toString();
button3.Text = "C".toString();
...
button9.Text = "I".toString();

But the code is too lengthy. Is there any way I can do this inside a loop? Something like this:

char x = 'A';
for(int i = 1; i<10;i++,x++)
{
    button[i].Text = x.toString();
}

Pls help

1
  • 4
    "A" is already a string. No need to add ToString to it . ;-) Commented Aug 3, 2014 at 9:04

1 Answer 1

2

You could add your Button controls to a list and iterate the list.

int charIndex = 65;
foreach (Button b in buttonList)
{
   b.Text = new String((char)charIndex, 1);
   charIndex++;
}

If you don't have nested controls and you want to get all the buttons to a list, you could do

List<Button> buttonList= Controls.OfType<Button>().ToList();

then iterate as above.

Sign up to request clarification or add additional context in comments.

2 Comments

Another thing that might be more readable is to use char[] characters = "ABCDEFGHILM".ToCharArray() and access the array to get the correct character.
@FabioMarcolini - That's a good idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.