简体   繁体   中英

Change picture box picture

I added picture box to my form and import 2 pictures, from properties under image property i choose the first picture when the application starting and inside my start button event i want to change my picture to the other picture. this is what i have try:

pbIndicator.Image = Image.FromFile(@"..\Resources\indicator_green.png");

but file not found exception error occurs.

您应该能够执行以下操作:

pbIndicator.Image = Resources.indicator_green;

Be sure that in the property window if the Build Action is on Content , and Copy to Output Directory is on Copy if newer .

If you want it to be content. Else use the answer Shadow Wizard gave.

As I wrote in the comment if indicator_green.jpg is an image included as resource via resource file ( Resources.resx ) then it won't be copied to output directory (it means it's in your project folder because it's used to build executable but it'll be embedded inside your assembly, not deployed standalone).

Resource files will (by default) place resources you add inside Resources folder (and then linked). You can always access them using generated code file for resources:

pbIndicator.Image = Properties.Resources.indicator_green;

You may change namespace Properties and property name according to what you have in your project (by default property name has the same name of the resource and then same name as original file).

Of course you're not forced to embed your resources in your assembly. If you want to deploy them as standalone files just right click Resources folder and add an existing file. In the properties window for that file select Copy always for Copy to output directory and et voila, you'll be able to read it with:

pbIndicator.Image = Image.FromFile(@"Resources\indicator_green.png");

Please note that Resources folder won't be a sub-directory of your output directory (do not forget that source files are not part of installation).

Anyway I suggest you do not build path like that, little bit better would be to do not rely on current folder:

pbIndicator.Image = Image.FromFile(
    Path.Combine(Application.StartupFolder, @"Resources\indicator_green.png");

You're not limited to Resources folder, you can do that with any folder (and with any name).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM