Change row color in inactive DataGridView

What is the best way to change the color of rows in a DataGridView when it is inactive ?

In the "real" world, I would like to use it to format all rows of a DataGridView after clicking a button, depending on some criteria.

To reproduce the behavior, try:
1. In the WinForms application, place the TabControl with two tabs. On the first tab, enter the button , on the second - DataGridView .
2. Use the following code:

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public int counter = 0;

        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Surname", typeof(string));
            dt.Rows.Add("Mark", "Spencer");
            dt.Rows.Add("Mike", "Burke");
            dt.Rows.Add("Louis", "Amstrong");

            dataGridView1.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            counter++;
            this.Text = "Event counter: " + counter.ToString();

            dataGridView1.Rows[1].DefaultCellStyle.BackColor = System.Drawing.Color.Red;
        }
    }
}

, , ( - ;) - ).

, tabPage2, tabPage2 - . , .

, tabPage2, , , tabControl1.SelectedIndex = 1;, tabControl1.SelectedIndex = 0; - "".

cell_painting, - , datagridview, .

- ?

,
Marcin

+3
1

datagridview ( ).

private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
}

- , , , DefaultCellStyle, - :

public partial class Form1 : Form
{

    private bool setcol;
    private bool painted;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        setcol = true;
        painted = false;
    }

    private void dataGridView1_Paint(object sender, PaintEventArgs e)
    {
        if (setcol && !painted)
        {
            painted = true;
            dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
        }
    }
}
+1

All Articles