Search code examples
c#listview

Determine column of header clicked in a ListView?


Simple question, I need to know the position (column) of a header in a ListView when I click it.

For non header cells, I use this:

private void listViewMine_DoubleClick(object sender, EventArgs e)
{
    Point mousePosition = myListView.PointToClient(Control.MousePosition);
    ListViewHitTestInfo hit = myListView.HitTest(mousePosition);
    int columnindex = hit.Item.SubItems.IndexOf(hit.SubItem);
}

which comes from:

Determine clicked column in ListView

Which doesn't work with header... I found nothing on the subject. Is there a way to obtain it?


Solution

  • The ColumnClick event will only fire if the ListView.View is set to Details. I am assuming this is what you mean by “header clicked” since there are no headers in any view except “Details”. If this is the case, then the ColumnClick event for the ListView should give you the value of the column header clicked.

    private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) {
      MessageBox.Show("Column " + e.Column.ToString() + " Clicked");
    }