Saturday, February 21, 2009

Dynamically add Picture box using C# delegate

The below code is just abstract just to show simple use of delegate

using System.Data;

using System.IO;
using System.Drawing;
using System.Text;
using System.Threading;
public partial class ImageView : Form{

Mydel a;

public delegate void Mydel(PictureBox p);
public ImageView(){
InitializeComponent();
}

private void ImageView_Load(object sender, EventArgs e){
a = new Mydel(Add);
Thread t = new Thread(load);
t.Start();
}

public void load(){

DirectoryInfo dinfo = new DirectoryInfo(@"F:\Mypics");
FileInfo[] finfo = dinfo.GetFiles();
Graphics g = panel1.CreateGraphics();
int x = 20;
int y = 20;
for (int i = 0; i

if (Image.FromFile(finfo[i].FullName) != null){

PictureBox p = new PictureBox();
p.Image = Image.FromFile(finfo[i].FullName);
p.SizeMode = PictureBoxSizeMode.StretchImage;
p.Left = x;
p.Top = y;
p.ImageLocation = finfo[i].FullName;
p.Width = 140;
p.Height = 90;
Object[] obj = new Object[1];
obj[0] = p;

Controls[Controls.IndexOf(panel1)].Invoke(a, obj);
x += 150;

if (x > this.Width-100){

y += 100;
x = 20;
}

}
if (i > 35)
break;

}

}

public void Add(PictureBox p) {

panel1.Controls.Add(p);

}

}

}

No comments:

Post a Comment