Click to See Complete Forum and Search --> : Problem Accessing Controls Inside TabPage


Four Symbols
February 20th, 2010, 04:45 PM
Basically, I have a huge amount of labels that correspond to notes on a guitar fretboard. When the form loads, I organize these into arrays so that it's easier to perform functions on them later.

Here's the code I'm using to convert the label into a label array:

Label[] lblFretboardInterval_0 = new Label[12];
int i = 0; while (i < 12)
{
lblFretboardInterval_0[i] = (Label)this.Controls["Label" + Convert.ToString(1 + i)];
}

For simplicity I've only showed one of the labels, but I have lblFretboardInterval_1, _2, _3 and so forth up to 11.

Now, Here's my problem: If I put the labels inside of a TabPage, the code above won't work. It's trying to find the labels, but since they're inside the TabPage it's not referencing correctly. I've researched this, but can't find a way to reference the labels when they are inside of a TabPage.

If anyone knows a way to do this I would be very thankful. Thanks in advance for your help!

BigEd781
February 20th, 2010, 09:08 PM
That is very fragile code and it will break often. Instead of doing that, just create a user control. Also the reason that you cannot access them from Form.Controls is because they are not in the Form's top level Controls collection, they are in the TabPage's Controls collection, so you would need a recursive function that iterates through all child controls as well.

One more note; it is a really bad idea to use the name of the control as a way to find it. That name can change for various reasons and now your program is broken. Why not just do this?


private List<Label> labels = new List<Label>( );

private void InitLabelCollection( )
{
foreach( Control c in tabPage1.Controls )
{
if( c is Label )
{
labels.Add( c );
}
}
}

Or, if the number of labels is always the same (as it seems to be since you are using teh literal value of '12'), just do this:

private void InitLabelCollection( )
{
foreach( Control c in tabPage1.Controls )
{
labels.Add( label1 );
labels.Add( label2 );
labels.Add( label3 );
// etc.
}
}

rliq
February 21st, 2010, 09:25 PM
Ed is correct... UserControl is the way to go.

In general when using tab pages, (IMHO) each tab page should contain ONE control... A UserControl that fills the page and acts as a container for all of the controls (be them Labels Buttons or other UserControls). Not only is this more maintainable (loosely coupled), but it is easier to adjust the layout if your Tab Control changes size.

Your FretboardUserControl could then even fire events, eg a Pluck Event, which passes the Note etc on to the main form for processing.... Who know's it could even post a C# !! Sorry my musical knowledge is limited to the Recorder and from your Id, I assume you are Jimmy Page. ;)

Four Symbols
February 23rd, 2010, 09:37 PM
Thanks both of you for your responses, I'm going to have to do some experimenting with those recommendations!