[c#] Changing datagridview cell color dynamically

I have a dataGridView object that is populated with data. I want to click a button and have it change the color of the background of the cell. This is what I currently have

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewColumn col in dataGridView1.Columns)
    {
            //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
            //col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
        dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
    }
} 

ALL of these three cause the table to be redrawn over itself in an overlapping manner and trying to re-size the tables becomes a mess. when clicking on a cell, the value remains highlighted and the backcolor doesn't change.

Q: How can I change the backcolor of an individual cell after the table exists?

This question is related to c# dynamic datagridview cell backcolor

The answer is


If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:

class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        if (value != null)
        {
            if ((bool) value)
            {
                cellStyle.BackColor = Color.LightGreen;
            }
            else
            {
                cellStyle.BackColor = Color.OrangeRed;
            }
        }
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}

}

Then in the code set CellTemplate property of your column to instance of your class

columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

Thanks it working

here i am done with this by qty field is zero means it shown that cells are in red color

        int count = 0;

        foreach (DataGridViewRow row in ItemDg.Rows)
        {
            int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
            if (qtyEntered <= 0)
            {
                ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
                ItemDg[1, count].Style.BackColor = Color.Red;

                ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory                       
            }
            ItemDg[0, count].Value = "0";//assign a default value to quantity enter
            count++;
        }

    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results

Examples related to cell

Excel doesn't update value unless I hit Enter Excel Define a range based on a cell value Link a photo with the cell in excel VBA setting the formula for a cell Changing datagridview cell color dynamically How to delete Certain Characters in a excel 2010 cell How do I change a single value in a data.frame? Set value for particular cell in pandas DataFrame using index Copying the cell value preserving the formatting from one cell to another in excel using VBA How to get html table td cell value by JavaScript?

Examples related to backcolor

Changing datagridview cell color dynamically