【发布时间】:2017-08-16 16:33:18
【问题描述】:
如何在 C# Forms 中向 ListView 添加图片?
我的程序获取目录的所有子文件夹,并能够在 ListView 中显示名称。
但我无法为每个列表视图项添加文件夹图标。
这是我到目前为止尝试过的代码:
string storedir =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\myfolder";
ImageList imgl = new ImageList();
//Get the folder icon from resources
imgl.Images.Add(Properties.Resources.folder);
DirectoryInfo dir = new DirectoryInfo(storedir);
foreach (DirectoryInfo getdirs in dir.GetDirectories("*.*")) {
ListViewItem lItem = listView1.Items.Add(getdirs.Name, imgl.Images.Count - 1);
}
没有成功:
谁能帮帮我?
编辑:
现在可以了。感谢@Gusman 和@LarsTech! 我在表单中添加了一个 ImageList 控件并将其命名为“imgl”。然后我在 ListView 控件上将它设置为 Small- 和 LargeImageList,最后我删除了
ImageList imgl = new ImageList();
谢谢!
【问题讨论】:
-
图片的索引必须以0为基础,所以不用
imgl.Images.Count使用imgl.Images.Count - 1 -
ListView控件需要通过LargeImageList和SmallImageList属性引用你的图片列表。
-
好的,我添加了“ - 1”,但仅此一项并没有改变任何东西(也更新了帖子),@LarsTech 这两个选项,Large 和 SmallImageList 都不允许我选择任何东西。它只是说“(无)”
-
补充:我添加了一个 ImageList 控件并将其命名为 imgl。现在可以了!谢谢! :)
-
可以使用图像列表添加最大 256x256 的图像。对于较大的图像,您需要进行所有者绘制列表视图。 - 如果您对答案感到满意,请考虑accepting it..!