【问题标题】:Datagrid view cell formatting issue in windows C# applicationWindows C# 应用程序中的 Datagridview 单元格格式问题
【发布时间】:2017-02-18 10:46:27
【问题描述】:

我已经从 sql 数据库动态加载数据网格视图。在基于特定列值的情况下,我必须更改单元格的背景颜色。

但它是这样显示的,

private void Grid_Log_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // Set the background to red for negative values in the Balance column.
            if (Grid_Log.Columns[e.ColumnIndex].Name.Equals("MStatus") || Grid_Log.Columns[e.ColumnIndex].Name.Equals("Status"))
            {
                if (e.Value.Equals("SUCCESS")||e.Value.Equals("Closed"))
                {
                    //e.CellStyle.BackColor = Color.Red;
                    //e.CellStyle.SelectionBackColor = Color.DarkRed;
                    //Grid_Log.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
                    Grid_Log.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                }
            }
        }

我已经尝试了上面的代码,但仍然出现。

【问题讨论】:

  • 我觉得你应该看看这个:stackoverflow.com/questions/26994457/…
  • 如果MStatus 的值为“SUCCESS”,您发布的代码会将背景颜色更改为红色,或者如果Status 的值为“已关闭”,则将背景颜色更改为红色。您应该检查e.Value 可能为空的可能性。我不确定图片应该代表什么,一个单元格还是整个网格?
  • 谢谢johnG,我已经解决了。当e.Value为null时会发生。

标签: c# windows winforms gridview datagridview


【解决方案1】:
private void Grid_Log_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (Grid_Log.Columns[e.ColumnIndex].Name.Equals("MStatus") || Grid_Log.Columns[e.ColumnIndex].Name.Equals("Status"))
            {
                if (e.Value!=null)
                {
                    if (e.Value.Equals("SUCCESS") || e.Value.Equals("Closed"))
                    {
                        //e.CellStyle.BackColor = Color.Red;
                        //e.CellStyle.SelectionBackColor = Color.DarkRed;
                        //Grid_Log.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
                        Grid_Log.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                    }
                }
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2018-06-05
    相关资源
    最近更新 更多