我想为单元格设置值时未处理异常

时间:2019-05-29 07:04:04

标签: c# datagridview cell-formatting

我正在使用查询来获取数据并显示在datagridview上。并使用单元格格式来调用函数(条件发生时上色行) 然后,当某些情况发生时,我想设置一个单元格值。代码是

    private void InventoryListGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        HighlightRow(sender, e.RowIndex, "Equipment");
    }

    private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        HighlightRow(sender, e.RowIndex, "Chemical");
    }
    private void HighlightRow(object sender, int index, string list)
    {
        DataGridView row = (sender as DataGridView);
        if (row[0, index].Value == null) return;

        Color bgColor = Color.LightGreen; //available
        Color foreColor = Color.Black;

        // status column
        if (row[4, index].Value.ToString() == "CHECKOUT")
        {
            bgColor = Color.Yellow; // Color.FromArgb(128, 128, 255);
        }

        // calibrate due
        if (bgColor == Color.LightGreen)
        {
            DateTime dueDate = Convert.ToDateTime(row[6, index].Value);
            DateTime today = DateTime.Now;
            TimeSpan diff = dueDate - today;
            if (diff.TotalDays <= 0)
            {
                bgColor = Color.Red;
                foreColor = Color.LightYellow;
                row[4, index].Value = list == "Chemical" ? "EXPIRED" : "OVERDUE";//************It shows this -> System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'

            }
            else if (diff.TotalDays <= 30)
            {
                if (list == "Chemical")
                {
                    bgColor = Color.LightGreen;
                }
                else
                {
                    bgColor = Color.LightCoral; // Color.FromArgb(255, 128, 128);
                }
            }
            else if (diff.TotalDays <= 90)
            {
                if (list == "Chemical" && diff.TotalDays <= 60)
                {
                    bgColor = Color.Orange;
                }
                else if (list == "Chemical")
                {
                    bgColor = Color.LightGreen;
                }
                bgColor = Color.Orange; // Color.FromArgb(255, 192, 128);
            }
        }

        System.Diagnostics.Debug.WriteLine("Coloring " + row[0, index].Value.ToString() + " with " + bgColor);
        // start coloring the row
        for (int i = 0; i < row.ColumnCount; i++)
        {
            row[i, index].Style.BackColor = bgColor;
            row[i, index].Style.ForeColor = foreColor;
        }
    }

下面的代码有未处理的异常吗?

row[4, index].Value = list == "Chemical" ? "EXPIRED" : "OVERDUE";

如何设置单元格的值?

1 个答案:

答案 0 :(得分:0)

我更改为使用另一种方法,该方法使用查询首先将值设置为在datagridView上显示,而不是在datagridView中显示的数据之后更改值。