Changing datagridview cell color based on condition

前端 未结 12 981
粉色の甜心
粉色の甜心 2020-12-02 20:36

I have loaded the data from database to datagridview and have two columns target value and volume where volume >target value that volume cell should be in green color and

12条回答
  •  抹茶落季
    2020-12-02 21:04

    Let's say you have to color certain cell (not all cells of the row) by knowing two things:

    1. Name or index of the column.
    2. Value which is gonna be inside of the cell.

    In thas case you have to use event CellFormatting

    In my case I use like this

    private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
         foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
         {
           if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
           {
              row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
           }
           else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
           {
              // row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row
    
              row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
           }
         }
    }
    

    And result you can see here

    So here you can access certain cell of the row in column by its name row.Cells["Decade1Hours"]

    How do you know this name? Well in my case i create column of DataGridView like this.

    var Decade1Hours = new DataGridViewTextBoxColumn()
    {
       Name = "Decade1Hours",
       Width = 50,
       DataPropertyName = "Decade1Hours",
       ReadOnly = true,
       DefaultCellStyle = new DataGridViewCellStyle()
           {
            Alignment = DataGridViewContentAlignment.MiddleCenter,
            ForeColor = System.Drawing.Color.Black,
            Font = new Font(font, FontStyle.Bold),
            Format = "n2"
          },
       HeaderCell = new DataGridViewColumnHeaderCell()
          {
              Style = new DataGridViewCellStyle()
                   {
                     Alignment = DataGridViewContentAlignment.MiddleCenter,
                     BackColor = System.Drawing.Color.Blue
                   }
           }
    };
    Decade1Hours.HeaderText = "Дек.1";
    dgvTrucksMaster.Columns.Add(Decade1Hours);
    

    And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).

    And code will lok like

     private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
      foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
      {
        if (Convert.ToInt32(row.Cells[1].Value) > 0 )
        {
          row.Cells[1].Style.BackColor = Color.LightGreen;
        }
      }
    }
    

提交回复
热议问题