Windows C#应用程序中的Datagrid视图单元格格式问题

时间:2017-02-18 10:46:28

标签: c# windows winforms gridview datagridview

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

enter image description here

但它显示如下,

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;
                }
            }
        }

我已尝试过以上代码,但仍然会发生。

1 个答案:

答案 0 :(得分:0)

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;
                    }
                }
            }
        }