Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I have a Datagridview DGV_Results,when I use the following code the cell background color always returs empty, but the row backcolor is working correctly.What could be the error??

C#
foreach (DataGridViewRow row in DGV_Result.Rows)
{
    int colindx = 0;
    rowindx++;

    foreach (DataGridViewCell cell in row.Cells)
    {
        colindx++;
        ws.Cells[rowindx, colindx].Value = cell.EditedFormattedValue;
        MessageBox.Show(row.DefaultCellStyle.BackColor.Name);
        if (cell.Style.BackColor == Color.Red)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Red);
        }
        else if (cell.Style.BackColor == Color.Yellow)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
        }
        else if (cell.Style.BackColor == Color.Green)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Green);
        }
        else
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.White);
        }


    }


}

-Manuprasad M
Posted
Comments
DamithSL 21-Jan-15 0:32am    
what is ws?

1 solution

Hello, the issue is the way you are using the cell.Style property.

DataGridViewCell on a row that do not have their own styling use the InheritedStyle property of the DataGridViewRow they are on.

Try this minor change:

C#
foreach (DataGridViewRow row in DGV_Result.Rows)
{
    int colindx = 0;
    rowindx++;
 
    foreach (DataGridViewCell cell in row.Cells)
    {
        colindx++;
        ws.Cells[rowindx, colindx].Value = cell.EditedFormattedValue;
        MessageBox.Show(row.DefaultCellStyle.BackColor.Name);
        if (cell.InheritedStyle.BackColor == Color.Red)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Red);
        }
        else if (cell.InheritedStyle.BackColor == Color.Yellow)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
        }
        else if (cell.InheritedStyle.BackColor == Color.Green)
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.Green);
        }
        else
        {
            ws.Cells[rowindx, colindx].Style.Fill.BackgroundColor.SetColor(Color.White);
        }
    }
}


Hope that helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900