Command Button (C#.Net VSN 2005)

Hi

I have 100 buttons on GroupBox of a form. ie., Button1, Button2....Button100. I need to change the Color of their texts in a single event. If so far, I don't need to mention

"this.BtnSurah11.ForeColor = System.Drawing.Color.Maroon;" for each and every buttons.

So is it possible to build up a loop for 100 sequences which define the object (button), from the loop can we change their property

For example

int i;

for (i=1;i<=100;i++)

{

String Str = "Button";

Str + i .forecolor = System.Drawing.Color.Maroon;

}

or

foreach (Control control in this.Controls)

{

if (control is Button)

control.ForeColor = System.Drawing.Color.Maroon;

}

if we can do like this (I know it will show us an error or it will not produce any result) we be able to minimise our codings. So advice me how to define a object in a loop thru which we can manipulate its property. Or notify me from your point of view.

Regards

M.N.Ahmed Sahib




Answer this question

Command Button (C#.Net VSN 2005)

  • laserbeam

    If what Brendan says doesn't work for you, you can always load all your buttons into an ArrayList or any object holding vector/array. You can then cast them as buttons (i.e. ((Button) list[index]).forecolor = ...)

  • vanilla_gorilla

    Your second example is the direction I would take... only I am guessing that the reason you ask about it is that it is not changing the buttons inside of the GroupBox

    From the looks of it I’m betting that that foreach loop is contained within your Form code and you are not seeing the expected results because it’s iterating through the wrong Controls collection... instead of doing it on this (likely the form), specify the group box name similar to this:

    foreach (Control control in groupBox1.Controls)

    {

    if (control is Button)

    control.ForeColor = System.Drawing.Color.Maroon;

    }

    Does this work for you



  • Command Button (C#.Net VSN 2005)