Hello,
I have been trying to get the last item added to my listview as selected. This does not mean I need to select the last item in the listview, I need the last one added.
(I know that for the last item I can use something like: listview.Items[Items.Count - 1].Selected = true. However, because of the item sorting, the last added item may not be the last one in the list)
I have wrote this method and I pass it the filename of the last item added and then I compare it against all items in the listview, if filename matches, then I set its selected property to true. However, this does not seem to work, anyone got some ideas as to why and how I could possibly implement this?
This is the code:
private void selectLastAdded(string lastAdded)
{
listView1.Items.Clear();
String[] files = Directory.GetFiles(folderBrowserDialog4.SelectedPath);
foreach (String file in files)
{
String fileExtension = Path.GetExtension(file);
if (fileExtension == ".jpg" || fileExtension == ".bmp" || fileExtension == ".png")
{
string fileName = Path.GetFileName(file);
FileInfo fileInfo = new FileInfo(file);
string creationDate = fileInfo.CreationTime.Date.ToString();
ListViewItem item = new ListViewItem(fileName);
long bytes = fileInfo.Length;
float megaB = (bytes / 1024f) / 1024f;
string subItem = megaB.ToString("0.00") + "MB";
item.SubItems.Add(subItem);
item.Tag = file;
listView1.Items.Add(item);
string filenameLastAdded = Path.GetFileName(lastAdded);
if (item.Text == filenameLastAdded)
{
listView1.Items[item.Index].Selected = true;
}
}
}
/**
foreach (ListViewItem myItem in listView1.Items)
{
string test = myItem.Tag.ToString();
string testfilename = Path.GetFileName(test);
string filenameLastAdded = Path.GetFileName(lastAdded);
if (testfilename == filenameLastAdded)
{
listView1.Items[myItem.Index].Selected = true;
}
}*/
}
Loading
Sam HobbsPosted May 13, 2011, 7:00 PM
When you add an item to the control (as in listView1.Items.Add) a ListViewItem is returned. You can save that item (or maybe just the index in the item) and use that. If you store the value in the same place for all, tehn that place will have the last one added, correct?
VulpesPosted May 13, 2011, 12:11 PM
1. You're clicking on the first item rather than on the headings to move focus back to the listview.
2. The first item is being selected as a result of some other event firing in the meantime.
B RamirezPosted May 13, 2011, 11:10 AM
I have replaced my code with yours. Strangely enough, using your code the first item is selected, even though the line "item.Selected = true;" is selecting the new added item as selected. Any ideas?
VulpesPosted May 13, 2011, 10:32 AM
To test that hypothesis, I'd try replacing this part of the code:
with this:
B RamirezPosted May 13, 2011, 10:25 AM
if (testfilename == filenameLastAdded)
{
listView1.Items[myItem.Index].Selected = true;
}