将文件夹中的图像添加到下拉列表 [英] Adding image from folder to dropdown list
问题描述
我想从文件夹中添加图像并在下拉列表中列出它.像我的应用程序一样,文件夹名称标志包含所有标志图像及其国家名称.如何将它们添加到下拉列表中.
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 .
推荐答案
您应包括System.IO
命名空间,并在表单中添加ImageList
.将其ImageSize
设置为适合您图像的尺寸.
You should include the System.IO
namespace and add an ImageList
to your form. Set its ImageSize
to a nice size for you images.
然后使用下面的代码来完成其余的工作!它将文件夹中的所有文件加载到ImageList
和ComboBox
的Items
中.请注意,它不加载文件名而是加载FileInfo
对象,因此它可以轻松显示名称而无需路径.还要注意,要在CombBox中显示图像,必须为owner-drawn
,如您所见,它很简单.
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);
}
这篇关于将文件夹中的图像添加到下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!