Handle click on a sub-item of ListView
20,084
Solution 1
You need to determine the column by its position:
private void listView_Click(object sender, EventArgs e)
{
Point mousePos = listView.PointToClient(Control.MousePosition);
ListViewHitTestInfo hitTest = listView.HitTest(mousePos);
int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
}
Solution 2
This is working well for me:
private void listView_MouseDown(object sender, MouseEventArgs e)
{
var info = listView.HitTest(e.X, e.Y);
var row = info.Item.Index;
var col = info.Item.SubItems.IndexOf(info.SubItem);
var value = info.Item.SubItems[col].Text;
MessageBox.Show(string.Format("R{0}:C{1} val '{2}'", row, col, value));
}
Solution 3
You can use the ListView.MouseClick
event as follows:
private void listView_MouseClick(object sender, MouseEventArgs e)
{
// Hittestinfo of the clicked ListView location
ListViewHitTestInfo listViewHitTestInfo = listView.HitTest(e.X, e.Y);
// Index of the clicked ListView column
int columnIndex = listViewHitTestInfo.Item.SubItems.IndexOf(listViewHitTestInfo.SubItem);
...
}
Related videos on Youtube
Author by
Steve Kero
Updated on July 14, 2022Comments
-
Steve Kero almost 2 years
How can I handle click on a sub-item of ListView (detail mode)? i.e. I need to detect what exactly column was clicked.
-
user1265146 about 10 yearsThis wouldn't work on a click event.. but did work on the double click event (.NET 4.5 :)
-
Gone Coding almost 6 yearsThis also works for MouseUp, MouseDown etc and is cleaner than the accepted answer. +1
-
AaA almost 6 yearsThis works on click event too, however you cannot place a break point on
Control.MousePosition
It somehow gets updated with new value when you move your mouse even if visual studio is on top, and you'll be spending hours scratching your head to why I click same point every time and still getting differentmousePos
-
jw_ over 4 yearsNote: in VS2019 ListView property page the MouseClick event is in "Action" group instead of the "Mouse" group
-
asgaut over 2 yearsI had to enable FullRowSelect on the listview for it to receive Click or MouseClick events when a subitem was clicked.