Sergio Tapia
Sergio Tapia

Reputation: 41128

How to access controls that are inside a TabControl tab?

This is all I have so far.

tabControl1.TabPages[0].???

I have a PictureBox inside of TabPage1 of my TabControl.

How can I change the image location with code and not the properties pane?

Upvotes: 7

Views: 17871

Answers (2)

Nathan Baulch
Nathan Baulch

Reputation: 20683

Unless you've set GenerateMember to false on the picture box or you're building the form dynamically you should be able to reference the picture box by its name:

pictureBox1.ImageLocation = "...";

Otherwise, assuming the picture box is the first control in the first tab page you can use the Controls collection:

var picBox = (PictureBox) tabControl1.TabPages[0].Controls[0];
picBox.ImageLocation = "...";

If you know there is exactly one picture box somewhere but you're not sure what page it's on or where on that page it is you can use Linq:

var picBox = tabControl1.TabPages.Cast<Control>()
    .SelectMany(page => page.Controls.OfType<PictureBox>())
    .First();
picBox.ImageLocation = "...";

Upvotes: 7

Alfred Myers
Alfred Myers

Reputation: 6453

Although the controls appear inside a container (as a TabControl), they're all defined on the form, so there is no need to access them through the container.

Instead of:


tablControl1.TabPages[0].MyContainedControl...

Simply type:


MyContainedControl...

Upvotes: 9

Related Questions