简体   繁体   中英

How to colorize current cell only in DataGridView

The code I have got is colorizing all cells of the row but I need to colorize a certain/current cell.

How it can be done?

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                ThemeColorView tc = (dataGridView1.Rows[e.RowIndex].DataBoundItem as ThemeColorView);

                if (tc != null)
                {
                    Color c = Color.FromName(tc.ColorType.Trim());
                    Brush b = new SolidBrush(c);

                    // I know something shoud be changed here ;)   
                    e.Graphics.FillRectangle(b, e.CellBounds);
                    e.PaintContent(e.ClipBounds); 

                    e.Handled = true;
                }
            }
        }

Try comparing the painted cell to the CurrentCell of the grid:

if (e.RowIndex > -1 && dataGridView1.CurrentCell != null) {
  if (e.ColumnIndex == dataGridView1.CurrentCell.ColumnIndex &&
      e.RowIndex == dataGridView1.CurrentCell.RowIndex) {
        e.Graphics.FillRectangle(Brushes.Green, e.CellBounds);
        e.PaintContent(e.CellBounds);
        e.Handled = true;
  }
}

BTW, make sure you dispose of any custom made Brushes and Pens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM