Problem with image in ListView in window form (C#)
I'm creating an window form UI consist of something like file browser (a ComboBox and a ListView with image in the first column of each item), view of ListView I used is Detail, I've add images to the SmallImageList, already test the images are not null and set image index for each item but the images still not shown.
this is my code
main_fileView.View = View.Details;
string[] files;
if (main_dirComboBox.Text != "")
{
string parent = main_dirComboBox.Text;
if (System.IO.Directory.Exists(parent))
{
files = System.IO.Directory.GetFiles(parent);
if (files != null)
{
main_fileView.Items.Clear();
ImageList img_list = new ImageList();
int n = 0;
ImageList small_img_list = new ImageList();
ImageList large_img_list = new ImageList();
for (int i = 0; i < files.Length; i++)
{
string file_name = files[i].Substring(files[i].LastIndexOf('\\') + 1, files[i].Length - (files[i].LastIndexOf('\\') + 1));
string file_type = file_name.Substring(file_name.LastIndexOf('.'), file_name.Length - file_name.LastIndexOf('.'));
//get icon image from system
Icon smallicon = Icons.IconFromExtension(file_type, Ic开发者_StackOverflow中文版ons.SystemIconSize.Small);
Icon largelicon = Icons.IconFromExtension(file_type, Icons.SystemIconSize.Large);
small_img_list.Images.Add(smallicon);
large_img_list.Images.Add(largelicon);
}
main_fileView.SmallImageList = small_img_list;
main_fileView.LargeImageList = large_img_list;
foreach (string file in files)
{
string file_name = file.Substring(file.LastIndexOf('\\')+1,file.Length-(file.LastIndexOf('\\')+1));
System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
string file_size = fileInfo.Length/1000+" kB";
string file_datemodified = fileInfo.LastWriteTime.ToString();
string file_createDate = fileInfo.CreationTime.ToString();
string[] item_ = { file_name, file_size, file_datemodified, file_createDate };
ListViewItem item = new ListViewItem(item_,n);
n++;
main_fileView.Items.Add(item);
}
}
}
}
i've try replace
ListViewItem item = new ListViewItem(item_,n);
with
ListViewItem item = new ListViewItem(file_name, n);
item.SubItems.Add(file_size);
item.SubItems.Add(file_datemodified);
item.SubItems.Add(file_createDate);
but the result is still the same, there are blank spaces in front of each text in first column, but no image shown.
LAST EDITED
Finally I've got it, it's my fault, the problem is not in this path of code, in other path of code there's creating new ImageList which I've forget to comment it out before test, this code work properly, THANKS everyone for the answer.
ps. I can't answer my own question within 8 hours cause of too little reputation
Considering that you show in ListView a details of a file selected in ComboBox, you use Details
view. In other words you see the grid on UI.
In this case you have to specify a special column for the row and push desired image in that cell.
You can have a look here for more complex solution:
ListView with Image on SubItems
精彩评论