I don't really understand why you would want to add a
PictureBox
from another class into your
Form
. If the
PictureBox
is to be shown on the
Form
it should belong to the
Form
and not any other class.
In the example code, the
Players
class should raise an event passing the path to the image, and the
Form1
class should subscribe to the event and create the
PictureBox
from the path in the arguments.
Something like this:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
public partial class Form1 : Form
{
private Players players;
public Form1()
{
InitializeComponent();
players = new Players();
players.NewPlayerImageRequest += new EventHandler<PathToImageEventArgs>(
players_NewPlayerImageRequest);
players.Initialize();
}
void players_NewPlayerImageRequest(object sender, PathToImageEventArgs e)
{
try
{
Image image = Image.FromFile(e.Path);
PictureBox pictureBox = new PictureBox();
pictureBox.Image = image;
pictureBox.Size = image.Size;
Controls.Add(pictureBox);
}
catch (FileNotFoundException ex)
{
MessageBox.Show("The file " + ex.Message + " could not be found");
}
}
}
public class Players
{
public event EventHandler<PathToImageEventArgs> NewPlayerImageRequest;
public const string DefaultImagePath = @"D:\asd.jpg";
public void AddPlayerImage(string path)
{
OnNewPlayerImageRequest(new PathToImageEventArgs(path));
}
public void Initialize()
{
AddPlayerImage(DefaultImagePath);
}
protected virtual void OnNewPlayerImageRequest(PathToImageEventArgs e)
{
EventHandler<PathToImageEventArgs> eh = NewPlayerImageRequest;
if (eh != null)
eh(this, e);
}
}
public class PathToImageEventArgs : EventArgs
{
private string path;
public PathToImageEventArgs(string path)
{
this.path = path;
}
public string Path
{
get { return path; }
}
}