hitTest.RowIndex始终为-1

时间:2010-11-22 13:05:33

标签: winforms c#-3.0

在项目中有一个DataGridView。

我有一些代码可以显示基于的信息 被点击的单元格。

我的问题是如何检测用户是否点击了列或行 标题(除了单元格之外的任何东西)。

所有这些都与'dataGridView1_CellMouseDown'方法有关,我正在使用 HitTest尝试检测用户点击的内容,但我只是 当用户点击一个单元格时,获取'TopLeftHeader'并且'None' 在其他地方,Row索引始终为-1

2 个答案:

答案 0 :(得分:2)

使用CellMouseDown事件为您提供相对于单击的单元格的坐标。

改为使用控件的MouseDown事件,它将为您提供基于控件的坐标。

请参阅the example on MSDN

答案 1 :(得分:0)

您仍然可以使用CellMouseDown事件处理程序。事实上我觉得它有点干净,因为使用MouseDown事件,你必须创建一个HitTest来获取所选行。

以下代码是等效的:

    private void dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        // If right-click
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            // Get selected row
            var selectedRow = dgvBatches.Rows[e.RowIndex];
        }
    }

    private void dgv_MouseDown(object sender, MouseEventArgs e)
    {
        // If right-click
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            // Get the selected row/column
            DataGridView.HitTestInfo info = dgvBatches.HitTest(e.X, e.Y);

            // Get selected row
            var selectedRow = dgvBatches.Rows[info.RowIndex];
        }
    }
相关问题