当选择datagridview单元格时显示工具提示



当单元格被选中时,如何显示datagridview的工具提示,而不是通过鼠标悬停,而是通过使用箭头键?

正如您所注意到的,您将无法使用DataGridView的内置工具提示。事实上,你需要禁用它,所以设置你的DataGridView的ShowCellToolTips属性为false(它是true默认)。

你可以使用DataGridView的CellEnter事件和一个常规的Winform工具提示控件来显示工具提示,当焦点从一个单元格改变到另一个单元格时,不管这是用鼠标还是箭头键完成的。

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) {
    var cell = dataGridView1.CurrentCell;
    var cellDisplayRect = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    toolTip1.Show(string.Format("this is cell {0},{1}", e.ColumnIndex, e.RowIndex), 
                  dataGridView1,
                  cellDisplayRect.X + cell.Size.Width / 2,
                  cellDisplayRect.Y + cell.Size.Height / 2,
                  2000);
    dataGridView1.ShowCellToolTips = false;
}

注意,我根据单元格的高度和宽度为工具提示的位置添加了一个偏移量。我这样做是为了让工具提示不会直接出现在单元格上;您可能需要调整此设置。

我用的就是Jay Riggs的答案。另外,因为我需要更长的持续时间,所以我必须添加此事件以使工具提示消失。

private void dataGridView_MouseLeave(object sender, EventArgs e)
{
    toolTip1.Hide(this);
}
        dgv.CurrentCellChanged += new EventHandler(dgv_CurrentCellChanged);
    }
    void dgv_CurrentCellChanged(object sender, EventArgs e)
    {
        // Find cell and show tooltip.
    }

最新更新