How do you highlight the row and/or column labels of a datagridview on mouseover of any cell (in c#)?

前端 未结 3 1498
太阳男子
太阳男子 2021-01-07 05:36

With a DataGridView control on a Windows form, when you move the mouse over a row label (or column label) it\'s (the label cell) background changes to a shade of blue (or ot

3条回答
  •  再見小時候
    2021-01-07 06:01

    You could override the OnCellPainting event to do what you want. Depending on the size of your DataGridView, you might see flickering, but this should do what you want.

    
        class MyDataGridView : DataGridView
        {
            private int mMousedOverColumnIndex = int.MinValue;
            private int mMousedOverRowIndex = int.MinValue;
    
            protected override void OnCellMouseEnter(DataGridViewCellEventArgs e)
            {
                mMousedOverColumnIndex = e.ColumnIndex;
                mMousedOverRowIndex = e.RowIndex;
                base.OnCellMouseEnter(e);
                base.Refresh();
            }
    
            protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
            {
                if (((e.ColumnIndex == mMousedOverColumnIndex) && (e.RowIndex == -1)) ||
                    ((e.ColumnIndex == -1) && (e.RowIndex == mMousedOverRowIndex)))
                {
                    PaintColumnHeader(e, System.Drawing.Color.Red);
                }
                base.OnCellPainting(e);
            }
    
            private void PaintColumnHeader(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, System.Drawing.Color color)
            {
                LinearGradientBrush backBrush = new LinearGradientBrush(new System.Drawing.Point(0, 0), new System.Drawing.Point(100, 100), color, color);
                e.Graphics.FillRectangle(backBrush, e.CellBounds);
                DataGridViewPaintParts parts = (DataGridViewPaintParts.All & ~DataGridViewPaintParts.Background);
                e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None;
                e.AdvancedBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.None;
                e.Paint(e.ClipBounds, parts);
                e.Handled = true;
            }
        }
    

提交回复
热议问题