change cells' forecolor on selectionchanged

Pankaj tripathi 185 Reputation points
2023-12-23T07:33:06.04+00:00

Hi ,

i have a datagridview which is load of some data . how do i change all the cells forecolor within a row when a row is selected and revert it back when it is unselected .

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,927 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,473 questions
0 comments No comments
{count} votes

Accepted answer
  1. gekka 12,021 Reputation points MVP Moderator
    2023-12-23T10:14:45.3033333+00:00
    using System;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Windows.Forms;
    
    public partial class MainForm : Form
    {
        public MainForm()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Column1");
            table.Columns.Add("Column2");
            table.Columns.Add("Column3");
            Random rnd = new Random();
            for (int i = 0; i < 10; i++)
            {
                table.Rows.Add(Enumerable.Range(1, table.Columns.Count).Select(_ => rnd.NextDouble().ToString()).ToArray());
            }
    
            DataGridView dgv = new DataGridView();
            dgv.DataSource = table;
            dgv.Dock = DockStyle.Fill;
            this.Controls.Add(dgv);
    
    
            dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgv.DefaultCellStyle.ForeColor = Color.Black;
            dgv.DefaultCellStyle.BackColor = Color.White;
            dgv.DefaultCellStyle.SelectionBackColor = Color.LightYellow; //dgv.DefaultCellStyle.BackColor
            dgv.DefaultCellStyle.SelectionForeColor = Color.Green;
    
            dgv.CellPainting += Dgv_CellPainting;
        }
    
        private void Dgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
    
            if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected)
            {
                if (e.ColumnIndex == dgv.CurrentCell.ColumnIndex && !dgv.IsCurrentCellInEditMode)
                {
                    e.Graphics.FillRectangle(Brushes.LightPink, e.CellBounds);
                    e.Paint(e.CellBounds, e.PaintParts & ~DataGridViewPaintParts.Background);
                    e.Handled = true;
                }
            }
        }
    }
    

    [2023-12-23T22:00Z+09:00] remove unnecessary code

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.