Cher
Cher

Reputation: 2947

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?

Upvotes: 0

Views: 2491

Answers (2)

Kevin Ritch
Kevin Ritch

Reputation: 11

THE TAG ATTRIBUTE IS THE CLUE

What I do is to store the Column Numbers (Nomenclature "KEY" & String of the Column Number) into the .TAG attribute in the Columnheader.

When you click on the tab in the listview, you can derive the Column Number from the transparent TAG.

It's the same way that I use the tag on Text Boxes for identifying fields in the associated database when editing things like Contact Records in a CRM Module of an ERP.

I happen to mostly develop in VB6 but the method is universal.

Sometimes the obvious is the easiest :-)

Upvotes: 0

JohnG
JohnG

Reputation: 9479

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");
}

Upvotes: 1

Related Questions