How to access controls that are inside a TabControl tab?

僤鯓⒐⒋嵵緔 提交于 2019-12-12 08:46:20

问题


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?


回答1:


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...



回答2:


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 = "...";


来源:https://stackoverflow.com/questions/1297442/how-to-access-controls-that-are-inside-a-tabcontrol-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!