Tuesday 3 April 2012

C# WinForm get Control object by string value, taking PictureBox as an example


C# WinForm: 


As Control is the base class for all components, e.g., combobox,label....and all components have their containers, this gives us a simple solution that we can select each component by it string ID directly instead of using component arrays.


e.g., we have lots of PictureBox components in our Form, we want to change the displayed Image for the PictureBox individually. 


The code is:


//All pictureboxs' id starts with "pictureBox", e.g., pictureBox1, pictureBox2....
PictureBox pic= (PictureBox) this.Controls["pictureBox" + PictureBoxID];
//Unboxing and PictureBoxID is a string.


//change its image!
pic.Image = null;
pic.Image = Image.FromFile(FilePath...);

No comments:

Post a Comment