開發winform程序的時候常常設計到要顯示多張圖片的問題,其解決思路通常是先遍歷文件夾中的全部圖片,而後再把這些圖片添加到ImageList控件中,最後再綁定顯示出來。這裏咱們介紹兩種綁定的方法:ide
(一)動態生成PictureBox綁定圖片this
(1)先在界面添加ImageList和PictureBox控件spa
(2)遍歷文件夾中的全部圖片,並添加到ImageList中設計
(3)根據圖片的數量來動態生成PictureBox,並依次綁定顯示3d
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 string[] arrFileNames = System.IO.Directory.GetFiles(@"E:\五月天\Q版五月天"); 7 Image img = null; 8 foreach (string name in arrFileNames) 9 { 10 img = Image.FromFile(name); 11 imageList1.Images.Add(img); 12 } 13 14 PictureBox pb; 15 for (int i = 0; i < arrFileNames.Length; i++) 16 { 17 pb = new PictureBox(); 18 pb.Width = 130; 19 pb.Height = 170; 20 pb.Image = imageList1.Images[i]; 21 pb.Location = new System.Drawing.Point(0, i * 160); 22 panel1.Controls.Add(pb); 23 } 24 } 25 }
(二)ListView綁定多張圖片code
其大概思路同上,不囉嗦了,直接附上代碼orm
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 try 7 { 8 List<string> tifNames = new List<string>(); 9 string path = @"E:\五月天\Q版五月天"; 10 DirectoryInfo TheFolder = new DirectoryInfo(path);//文件路徑 11 imgListPhoto.Images.Clear(); 12 for (int i = 0; i < TheFolder.GetFiles().Length; i++) //遍歷文件夾 13 { 14 if (TheFolder.GetFiles()[i].Length > 0 && TheFolder.GetFiles()[i].Extension == ".jpg") //或者jpg,png 文件大小要大於0且是圖片文件 15 { 16 Image image = Image.FromFile(TheFolder.GetFiles()[i].DirectoryName + "\\" + TheFolder.GetFiles()[i].Name); //獲取文件 17 tifNames.Add(TheFolder.GetFiles()[i].Name);//添加文件名 18 imgListPhoto.Images.Add(image);//添加圖片 19 } 20 } 21 //初始化設置 22 this.listView1.View = View.LargeIcon; 23 this.listView1.LargeImageList = this.imgListPhoto; 24 25 //開始綁定 26 this.listView1.BeginUpdate(); 27 this.listView1.Items.Clear(); 28 ListViewItem items = new ListViewItem(); 29 items.SubItems.Clear(); 30 for (int i = 0; i < tifNames.Count; i++) 31 { 32 ListViewItem lvi = new ListViewItem(); 33 lvi.ImageIndex = i; 34 lvi.Text = tifNames[i]; 35 this.listView1.Items.Add(lvi); 36 Thread.Sleep(200); 37 } 38 this.listView1.EndUpdate(); 39 } 40 catch (Exception ex) 41 { 42 //MessageBox.Show("Error"); 43 throw new Exception(ex.Message); 44 } 45 } 46 }
我的建議仍是用ListView,而動態生成控件則可做爲一種思路,在其餘不少方面均可以用到的blog