Adding image from folder to dropdown list

血红的双手。 提交于 2019-12-13 10:17:11

问题


I want to add images from folder and list it in dropdown . Like my application has folder name flags containing all the flags images and their country name. how do I add them to dropdown .


回答1:


Try using the System.IO.Directory.GetFiles and System.IO.Path.GetFileName

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx

Something like (haven't tried it)

// Process the list of files found in the directory. 
string [] files = Directory.GetFiles(yourDirectory);
foreach(string file in files) {
    string language = Path.GetFileName(file);
    ddlFlags.Items.Add(new ListItem(language, file));
}

Next time, improve your question by describing what you have tried so far, then it would be easier to help you.




回答2:


You should include the System.IO namespace and add an ImageList to your form. Set its ImageSize to a nice size for you images.

Then use the code below to do the rest! It loads all files in a folder into both an ImageList and into the Items of a ComboBox. Note that it loads not the filenames but FileInfo objects, so that it can easily display the names without the path. Also note that to display images in a CombBox it has to be owner-drawn, which, as you can see it pretty straight-forward..

Here is the code to use & study:

  using System.IO;
  //..

  // load whereever you like
  // e.g. in the From.Load event or after InitializeComponent();

  var images = Directory.GetFiles(yourImageFolder, "*.jpg");
  foreach (string file in images)
  {
      imageList1.Images.Add(file, new Bitmap(file));
      comboBox1.Items.Add(new FileInfo(file));
  }
  comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
  comboBox1.DrawItem += comboBox1_DrawItem;
  comboBox1.ItemHeight = imageList1.ImageSize.Height;


  void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
  {
     FileInfo FI = (FileInfo)comboBox1.Items[e.Index];
     e.Graphics.DrawImage(imageList1.Images[FI.FullName], e.Bounds.Location);
     e.Graphics.DrawString(FI.Name, Font, Brushes.Black,
            e.Bounds.Left + imageList1.ImageSize.Height + 3, e.Bounds.Top + 4);
  }


来源:https://stackoverflow.com/questions/26624619/adding-image-from-folder-to-dropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!