Wednesday, September 12, 2012

Change DataGridView Cell Cursor

The .NET data grid view is a nice grid control which allows a lot of customization and can fit well in many scenarios. However, if you want to change the cursor of a specific data grid view cell when the mouse is over it (a.k.a. mouse hover), then you will have some hard time. Fortunately, there's a way to do this. You have to handle the CellMouseEnter and the CellMouseLeave events, changing the cursor of the data grid view to the desired one in the CellMouseEnter event handler and restoring it in the CellMouseLeave event handler.

The following sample source code demonstrates how to change the mouse cursor over all cells of a data grid view to a hand cursor:

private void dgData_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (IsValidCellAddress(e.RowIndex, e.ColumnIndex))
    {
        dgData.Cursor = Cursors.Hand;
    }
}
private void dgData_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    if (IsValidCellAddress(e.RowIndex, e.ColumnIndex))
    {
        dgData.Cursor = Cursors.Default;
    }
}

private bool IsValidCellAddress(int rowIndex, int columnIndex)
{
    return rowIndex >= 0 && rowIndex < dgData.RowCount &&
        columnIndex >= 0 && columnIndex <= dgData.ColumnCount;
}

Note that the IsValidCellAddress method is used to determine whether the cursor of the cell at the given address should be changed to hand cursor or not. The provided implementation simply returns true for any address that corresponds to a valid data grid view cell.

Finally, do not forget to subscribe to the CellMouseEnter and the CellMouseLeave events:

dgData.CellMouseEnter += new System.Windows.Forms.DataGridViewCellEventHandler(dgData_CellMouseEnter);
dgData.CellMouseLeave += new System.Windows.Forms.DataGridViewCellEventHandler(dgData_CellMouseLeave);

See also:

1 comment: