Changing datagridview cell color based on condition

前端 未结 12 1040
粉色の甜心
粉色の甜心 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 20:55

    Without looping it can be achived like below.

    private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
    
            FormatRow(dgEvents.Rows[e.RowIndex]);
    
        }
    
    private void FormatRow(DataGridViewRow myrow)
        {
            try
            {
                if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
                {
                    myrow.DefaultCellStyle.BackColor = Color.Red;
                }
                else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
                {
                    myrow.DefaultCellStyle.BackColor = Color.Yellow;
                }
                else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
                {
                    myrow.DefaultCellStyle.BackColor = Color.LightGreen;
                }
            }
            catch (Exception exception)
            {
                onLogs?.Invoke(exception.Message, EventArgs.Empty);
            }
        }
    

提交回复
热议问题