Khaled Khaled
Khaled Khaled

Reputation: 25

how to set DataGridViewButtonCell BackColor using htmlColor?

I'm struggling since 2 days to with this problem.

I have an XML file which contains Colors as htmlColor Code, in my program I have a DataGridView which is showing me the values in hexCodes, and I can click on it and change the color value with a ColorDialog and the then set the cell BackColor to the selected Color and gives me the hexCode back as new value.

sorry I cant post a picture asI dont have 10 reputaions (I'm new)

what I want is that when I open the XML file in my programm, the cells should have the BackColor of what is wrriten inside the cell.

I tried this but doesn't work :(

private void dgvColors_CellFormatting(object sender, 
                                      DataGridViewCellFormattingEventArgs e)
{
  Theme theme = new Theme();
  foreach (KeyValuePair<string, Color> colour in theme.Colors)
         dgvColors.Columns["colKey"].DefaultCellStyle.BackColor = 
                   ColorTranslator.FromHtml(colour.Value.ToString());      
}

Upvotes: 0

Views: 781

Answers (2)

Khaled Khaled
Khaled Khaled

Reputation: 25

So the problem was with the ColorTranslator(),

it works well with this version of code :

 private void dgvMenuColors_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
foreach (DataGridViewRow row in dgvMenuColors.Rows) 
{ 
row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml(row.Cells[1].Value.ToString()); 
} 
} 

:D

Upvotes: 0

TaW
TaW

Reputation: 54453

After you have set the FlatStyle to Flat you can change the Backcolor for each cell. With the Normal style you only see a 1 pixel wide frame around the Button.

This example creates DataGridViewButtonCells and paints these Cells after the DGV has been loaded:

for (int r = 0; r < DGV.Rows.Count; r++)
{
    DGV[4, r] = new DataGridViewButtonCell();
    ((DataGridViewButtonCell)DGV[4, r]).Style.BackColor = Color.OrangeRed;
    ((DataGridViewButtonCell)DGV[4, r]).FlatStyle = FlatStyle.Flat;   
    ((DataGridViewButtonCell)DGV[4, r]).Value = r + "RR";
}

Your code should be adaptable if you get the hex values right.

Upvotes: 1

Related Questions