0

我在下面有这两个代码:

方法:

public void GetGridColor()
{
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        if (dataGridView1.Rows[i].Cells[0].Value.ToString() != "")
        {
            if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "Normal")
            {
                dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(157, 196, 230);
            }

            if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "Critical")
            {
                dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(47, 117, 181);
            }

            if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "High")
            {
                dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(31, 78, 120);
            }
        }
    }
}

单元格格式化事件:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells[0].Value.ToString() != "")
                {
                    if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "Normal")
                    {
                        dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(157, 196, 230);
                    }

                    if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "Critical")
                    {
                        dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(47, 117, 181);
                    }

                    if (dataGridView1.Rows[i].Cells[10].Value.ToString() == "High")
                    {
                        dataGridView1.Rows[i].Cells[10].Style.BackColor = Color.FromArgb(31, 78, 120);
                    }
                }
            }
        }

基本上应该做同样的事情。但它会引发 System.NullReferenceException。

现在,如果我将其更改为

if (dataGridView1.Rows[i].Cells[0].Value != null)

在 CellFormatting 事件中它解决了这个问题。我承认缺乏一些编程知识,但我的问题是没有更改任何 FormattedValue 或提供从单元格值到显示值的自定义转换,为什么当 Cells[0] 不包含时会引发空异常错误我的样本数据上的空值?ToString()而且,当我在具有不同但几乎完全相同的示例数据的不同 datagridview(我们称之为 datagridview2)上应用相同的代码时,不会显示任何错误。还阅读此内容以尝试了解错误显示DataGridView CellFormating的原因。

4

0 回答 0