views:

119

answers:

1

Hello folks,

I am using Visual C# 2008 Express edition.

If at design time I have a form [myMainForm],
to which I have added a TabControl [myTabControl],
and myTabControl has a single tabPage [myTabPage],
and to this tabPage I have added a tableLayoutPanel [myTableLayoutPanel],
and to myTablelayoutPanel I have added ten buttons (button1, button2, button3, etc).

At runtime I want to populate a data structure with references to all the ten buttons I have added to myTableLayoutPanel. I want to work with the references to the buttons in the simplest, most efficient way possible. Is a for...next loop in conjunction with an array the best approach to tackle the problem?

I realise that I could add the buttons programmatically to the panel, but if I do that I will have to tweak their visual settings in code as well which I would rather avoid in order to keep my code as clean and simple as possible.

If someone could post a few lines of code to get me going on this I'd be grateful.

Thanks for taking the time to read this. Happy coding.

Regards,

The Thing

+1  A: 

In C#3 (in VS 2008), you could set up a compile-time array using the array initializer syntax:

var buttons = new [] { button1, button2, ... button10 };

alternatively, you could reflect on all the fields and filter the buttons, along the lines of

using System.Linq;

// tlp being your TablelayoutPanel instance
var buttons = tlp.GetType().GetFields().Select(f => f.GetValue(tlp)).Where(v => v is Button).ToArray();

This gets all the buttons -- you might want to add a Where(f => SomeTestOn(f.Name)) filter before the Select if you want to filter out those fields except with some known naming pattern indicating that they are the buttons you actually want.

Steve Gilham