Datagridview不会改变单元格颜色

时间:2017-10-27 08:24:40

标签: c# datagridview

我已经尝试了一切来改变颜色。我已阅读了很多stackoverflow帖子,但没有找到我的答案。在我使数据表从数据库填充数据之前,颜色已更改。之后,他们不再改变颜色。这是我在CellFormatting事件中触发的代码。

        public ScheduleUserControl()
    {
        InitializeComponent();
        dataGridView.CellClick += (s, e) => OnCellClick(e.ColumnIndex, e.RowIndex);
        dataGridView.CellFormatting += (s, e) => CellFormating(e.ColumnIndex, e.RowIndex);
        btnAll.Click += (s, e) => Filter(Filters.All);
        btnHourly.Click += (s, e) => Filter(Filters.Hourly);
        btnSalary.Click += (s, e) => Filter(Filters.Salary);
    }

private void CellFormating(int c, int r)
    {
        var cell = dataGridView[c, r];
        var tagObject = cell.Tag;
        if (tagObject == null)
        {
            cell.Style.ForeColor = Color.Black;
            cell.Style.BackColor = Color.White;
        }
        else
        {
            var tagType = tagObject.GetType();
            if (tagType == typeof(DayOff))
            {
                var avail = (DayOff)tagObject;
                if (avail != null)
                {
                    cell.Style.ForeColor = Color.White;
                    cell.Style.BackColor = Color.Firebrick;
                }
            }
            else
            if (tagType == typeof(DayOffRequest))
            {
                var request = (DayOffRequest)tagObject;
                if (request.Status == DayOffRequest.RequestStatus.Approved)
                {
                    cell.Style.ForeColor = Color.Black;
                    cell.Style.BackColor = Color.SkyBlue;
                }
                else
                if (request.Status == DayOffRequest.RequestStatus.Pending)
                {
                    cell.Style.ForeColor = Color.Black;
                    cell.Style.BackColor = Color.LightGoldenrodYellow;
                }
            }
            else
            if (tagType == typeof(Shift))
            {
                cell.Style.ForeColor = Color.White;
                cell.Style.BackColor = Color.Green;
            }
        }
    }

任何帮助都会非常感激。调试和单步调试表示它执行了cell.style更改,但datagridview只是没有显示这些更改。

1 个答案:

答案 0 :(得分:0)

您正在通过更改string street = Request.Form["streetName"]; 方法中的单元格样式来创建递归,这可能会导致意外结果。因此,请尝试在不同的事件中设置您的单元格样式,例如CellFormating()