Why don't I have an Items property in listView1?
When adding files to listView1 in this method, I have an Items property.
private void AddFiles(string strPath)
{
listView1.BeginUpdate();
listView1.Items.Clear();
iFiles = 0;
try
{
DirectoryInfo di = new DirectoryInfo(strPath + "\\");
FileInfo[] theFiles = di.GetFiles();
foreach(FileInfo theFile in theFiles)
{
iFiles++;
ListViewItem lvItem = new ListViewItem(theFile.Name);
lvItem.SubItems.Add(theFile.Length.ToString());
lvItem.SubItems.Add(theFile.LastWriteTime.ToShortDateString());
lvItem.SubItems.Add(theFile.LastWriteTime.ToShortTimeString());
listView1.Items.Add(lvItem);
}
}
catch(Exception Exc) { statusBar1.Text = Exc.ToString(); }
listView1.EndUpdate();
}
But now I want to add properties, so when I do right click on the file it will show the context menu:
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int index = listView1.IndexFromPoint(e.Location);
if (index != ListBox.NoMatches)
{
listJobs.SelectedIndex = index;
Job job = (Job)listJobs.Items[index];
ContextMenu cm = new ContextMenu();
AddMenuItem(cm, "Run", QueueForRun, job).Enabled = !job.Pending;
AddMenuItem(cm, "Cancel run", CancelQueueForRun, job).Enabled = (job.State == JobState.Pending || job.State == JobState.Running);
AddMenuItem(cm, "Open folder", OpenFolder, job);
cm.Show(listJobs, e.Location);
}
}
}
This time I have no IndexFromPoint and also no elements
source to share
Since it IndexFromPoint()
is a method ListBox
, it ListView
does not. There ListView
is a method GetItemAt()
to achieve the same result.
var item = listView.GetItemAt(e.Location.X, e.Location.Y);
if (item != null) {
listJobs.SelectedIndex = item.Index; // Assuming listJobs is a ListBox
}
EDIT : as per your comment, if listJobs
too ListView
, then it doesn't have SelectedIndex
, but it does SelectedIndices
, just:
listJobs.SelectedIndices.Clear();
listJobs.SelectedIndices.Add(item.Index);
You must clear the list first, because the default MultiSelect
is there true
, then you can select multiple items.
source to share