B Ramirez

B Ramirez

  • NA
  • 6
  • 8.8k

Set last item added (not the last item in the listview) to listview as selected item

May 13 2011 9:22 AM
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;
}
}*/
}

Answers (5)