【问题标题】:How to identify the specific cell hovered over in DataGridView如何识别 DataGridView 中悬停的特定单元格
【发布时间】:2015-08-08 09:23:28
【问题描述】:

我在所有 datagridview 行的末尾放了一张图片,以便在按下时删除行。 我想在特定单元格鼠标悬停时更改该图片的颜色(以表明它是用户的交互式按钮)。

但是,在所有解决方案中,我发现完整的 DGV 鼠标悬停是可以解释的。 我需要什么:了解如何在单元格鼠标悬停期间找到悬停的特定单元格

【问题讨论】:

  • 你的目标是什么:Winforms? WPF? ASP? ...?? 总是相应地标记您的问题! - 对于winforms:看看DataGridView.Hittest! - 另请注意,每次 MouseEnter,MouseHover 只会触发一次。因此,您可能需要更多逻辑或直接使用 MouseMove。

标签: c# winforms datagridview cell


【解决方案1】:

如果这是 WindowsForms:

//when mouse is over cell
    private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Black;
        }
    }
//when mouse is leaving cell
    private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
        }
    }

【讨论】:

    【解决方案2】:

    老问题,@titol 的回答很好,但我不喜欢为此使用事件CellMouseMove(它触发得太频繁了)。

    我建议在鼠标输入CellMouseEnter 时进行捕捉,当然还有CellMouseLeave。像这样:

        void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var gv = sender as DataGridView;
            var column = gv.Columns[e.ColumnIndex];
            if (myLogicToCheckIfIsTrashButtonColumn(column)) {
                gv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Black;
                gv.InvalidateCell(gv.Rows[e.RowIndex].Cells[e.ColumnIndex]);
            }
        }
    
        void downloadFilesGv_CellMouseLeave(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var gv = sender as DataGridView;
            var column = gv.Columns[e.ColumnIndex];
            if (myLogicToCheckIfIsTrashButtonColumn(column)) {
                gv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
                gv.InvalidateCell(gv.Rows[e.RowIndex].Cells[e.ColumnIndex]);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-05-18
      • 2012-12-23
      • 2015-11-03
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多