根据条件更改datagridview单元格颜色

pre*_*thi 27 c# datagridview winforms

我已经将数据从数据库加载到datagridview并且有两列目标值和体积,其中体积>目标值,体积单元格应为绿色,体积<目标值,然后体积应为红色.我尝试过,但我无法做到.

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    if (dataGridView1.Rows.Count > 0 && dataGridView1.Columns.Count > 0)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if (Volume > target value)
            {
                cell.Style.BackColor = Color.AliceBlue;
            } 
Run Code Online (Sandbox Code Playgroud)

Roh*_*hit 21

你需要这样做

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow Myrow in dataGridView1.Rows) 
    {            //Here 2 cell is target value and 1 cell is Volume
        if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition 
        {
            Myrow .DefaultCellStyle.BackColor = Color.Red; 
        }
        else
        {
            Myrow .DefaultCellStyle.BackColor = Color.Green; 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

同时还要看一下Cell Formatting

  • 这不是非常低效吗?由于每次重绘任何单元格都会重复所有记录.如果你采用这种方法,整个`foreach`子句不必在CellFormatting处理程序中,但它应该是`dataGridView1_DataBindingComplete`. (19认同)
  • 或者使用var Myrow = dataGridView1.Rows [e.RowIndex]而不是循环 (4认同)
  • 这是一个糟糕的解决方案,代码会迭代每个单元格的所有行. (4认同)

Sim*_*mon 20

我可能建议不要在每次调用CellFormating时循环遍历每一行,因为每次需要刷新一行时都会调用它.

Private Sub dgv_DisplayData_Vertical_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv_DisplayData_Vertical.CellFormatting
        Try

            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "6" Then

                e.CellStyle.BackColor = Color.DimGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "5" Then
                e.CellStyle.BackColor = Color.DarkSlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "4" Then
                e.CellStyle.BackColor = Color.SlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "3" Then
                e.CellStyle.BackColor = Color.LightGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "0" Then
                e.CellStyle.BackColor = Color.White
            End If

        Catch ex As Exception

        End Try

    End Sub
Run Code Online (Sandbox Code Playgroud)


dot*_*NET 17

Kyle和Simon的答案是对CPU资源的严重浪费.CellFormattingCellPainting事件发生的次数太多,不应该用于应用样式.以下是两种更好的方法:

如果DataGridView或至少决定单元格样式的列是只读的,则应更改RowsAdded事件中行的DefaultCellStyle .添加新行时,此事件仅发生一次.应该在那时评估条件,并且DefaultCellStyle应该在其中设置行.请注意,DataBound情况也会发生此事件.

如果您的DataGridView或那些列允许编辑,您应该使用CellEndEditCommitEdit更改事件DefaultCellStyle.


Dev*_*per 6

假设您必须通过了解两件事来为某些单元格(不是该行的所有单元格)着色:

\n\n
    \n
  1. 列的名称或索引。
  2. \n
  3. 值将位于单元格内部。
  4. \n
\n\n

在这种情况下,您必须使用事件CellFormatting

\n\n

就我而言,我这样使用

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

结果你可以在这里看到

\n\n

在此输入图像描述

\n\n

因此,在这里您可以通过名称访问列中行的某些单元格\nrow.Cells["Decade1Hours"]

\n\n

你怎么知道这个名字?\n在我的例子中,我像这样创建 DataGridView 列。

\n\n
var Decade1Hours = new DataGridViewTextBoxColumn()\n{\n   Name = "Decade1Hours",\n   Width = 50,\n   DataPropertyName = "Decade1Hours",\n   ReadOnly = true,\n   DefaultCellStyle = new DataGridViewCellStyle()\n       {\n        Alignment = DataGridViewContentAlignment.MiddleCenter,\n        ForeColor = System.Drawing.Color.Black,\n        Font = new Font(font, FontStyle.Bold),\n        Format = "n2"\n      },\n   HeaderCell = new DataGridViewColumnHeaderCell()\n      {\n          Style = new DataGridViewCellStyle()\n               {\n                 Alignment = DataGridViewContentAlignment.MiddleCenter,\n                 BackColor = System.Drawing.Color.Blue\n               }\n       }\n};\nDecade1Hours.HeaderText = "\xd0\x94\xd0\xb5\xd0\xba.1";\ndgvTrucksMaster.Columns.Add(Decade1Hours);\n
Run Code Online (Sandbox Code Playgroud)\n\n

好吧...您需要例如对行中的某些单元格进行着色,例如 ##1 4 5 和 8 您必须使用单元格索引(从 0 开始)。

\n\n

代码看起来像

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