0

If I want to catch events on clicking RMB on Col1 and Col2, and events should be different, is there any chance to do that ?

enter image description here

Steven
  • 185
  • 1
  • 5
  • 11
  • 1
    Use the MouseDown event and call ListView.HitTest() to see what was clicked. And fire your own event accordingly. – Hans Passant Sep 02 '12 at 19:01
  • Take a look at http://stackoverflow.com/questions/7844306/can-i-detect-if-a-user-right-clicked-on-a-listview-column-header-in-winforms – coolmine Sep 02 '12 at 19:31

2 Answers2

2

as @HansPassant said add the mouseup event

void listview1_MouseUp(object sender, MouseEventArgs e)
    {
        ListViewItem item = listview1.GetItemAt(e.X, e.Y);
        ListViewHitTestInfo info = listview1.HitTest(e.X, e.Y);

        if ((item != null) && (info.SubItem != null))
        {
            //item.SubItems.IndexOf(info.SubItem) gives the column index
            MessageBox.Show(item.SubItems.IndexOf(info.SubItem).ToString());
        }
    }
S3ddi9
  • 2,121
  • 2
  • 20
  • 34
  • thank you, Is it possible to do the same with `TreeView`, separate mouse click events on text area and other field of node if I use `myTreeView.FullSelectRow = true` ? – Steven Sep 03 '12 at 11:13
  • what do you want to retrieve here, in the listview you wanted the column index ,here ???? *the level may be* @Steven – S3ddi9 Sep 03 '12 at 14:17
  • just want to know where the click has been, for example: if in the text area then `true`, otherwise `false`, just want to know location – Steven Sep 03 '12 at 14:46
  • yes for sure replace `ListViewItem` by `TreeNode` and `ListViewHitTestInfo` by `TreeViewHitTestInfo` if `item` is null you're clicking out , else if (`info.Node` is null and item isn't) so you clicked at the expand button (+) else you selected your item – S3ddi9 Sep 03 '12 at 14:53
0

Use DataGridView insted of ListView. DataGridView already supports cell click:

    private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        string message = "You have clicked " + (e.ColumnIndex + 1).ToString() + " cell inside " + (e.RowIndex + 1).ToString() + " row!";
        MessageBox.Show(message, "Click info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

ListView is not ment to be used with tabular data. It's primary use is for lists, good example is Windows Explorer.

Gregor Primar
  • 6,759
  • 2
  • 33
  • 46