[ACCEPTED]-How to get control(s) from TabPage in C#?-winforms

Accepted answer
Score: 11

If this is WinForms, it would just be:

if (selectedTab.Controls.ContainsKey("rtb"))
  RichTextBox selectedRtb = (RichTextBox)selectedTab.Controls["rtb"];

if 2 rtb is the name of the RichTextBox control.

When 1 creating your control, add the name to it:

RichTextBox rtb = new RichTextBox();
rtb.Name = "rtb";
Score: 7

The reason your approach is not working 6 is because your are trying to find it by 5 using the control's name property.

Looking 4 at your code you are not setting the Name property. If 3 you can generate a known name ahead of time 2 you can use that when looking for the control.

You 1 can also try this:

var rtb = tabControl.SelectedTab.Controls.Cast<Control>()
                                .FirstOrDefault(x => x is RichTextBox);
Score: 1

Philip Fourie answer is pretty good, made me realize 5 that you can actually have the Design generating 4 or not a name for the control.

GenerateMember in Design

Somehow, I 3 got the GenerateMember set to false, once 2 turning it back on I could access the control 1 directly by it's name.

More Related questions