|
I have 1 Usercontrol. In it I load an image from code. But when I go to Form1 and put this control into form, I get an error that he can not find the image, but the image is there, and the root is correct from code. When I run the application, is working fine, loading the correct image. What setting I miss?
Thanks and here is the code:
public partial class Equipment : UserControl
{
public Equipment(){InitializeComponent();}
string path = Application.StartupPath;
PictureBox pictureBox3429= new PictureBox();
public void Equipment_Load(object sender, EventArgs e)
{
panel1.BackgroundImage = Image.FromFile(path + "\\unit.jpg");
try
{
}
catch (Exception) { throw; }
}
}
modified 18-Jan-13 10:34am.
|
|
|
|
|
Instead of rethrowing the exception (which is a bit redundant - why catch it if you only throw it again), put up a messagebox or write the output (Debug.WriteLine); sounds like the designer is running it in a different path, and that's what you want to check.
Also, if it throws an exception, paste it here; it holds hints on whats wrong and how to solve it.
|
|
|
|
|
It's because the StartupPath is not what you think it is. Testing this on my system causes the designer view of the form to show an error message in HTML, helpfully rendered as one very long line. Carefully scrolling through it reveals that it looking for the image
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\pic.jpg
In a simplified test I place the image directly onto an otherwise empty user control. I thought that the correct thing to do would be to stop the designer attempting to load the image like this:
public partial class ImageControl : UserControl {
String path;
public ImageControl() {
InitializeComponent();
path = Application.StartupPath;
}
private void ImageControl_Load(object sender, EventArgs e) {
if (!DesignMode) {
BackgroundImage = Bitmap.FromFile(Path.Combine(path, "pic.jpg"));
}
}
}
Job done you might think, but no, as this allows the form to render properly with the image displayed. So what is going on? Actually I don't know, but the only reasonable explanation is that the designer loads the form more than once, in DesignMode where the path is incorrect and at least once more, not in DesignMode, where the path is correct.
|
|
|
|