首页 > 解决方案 > 更改单元格值C#后如何在线更改datagridview中的行颜色?

问题描述

如何在输入单元格值时更改 datagridview 中的行颜色,我使用了以下代码和 cellFormatting 事件,但是当输入下限和上限之间的值时,它给出的错误输入字符串格式不正确

private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (dgvResult.Rows[e.RowIndex].Cells["Result"].Value == DBNull.Value)
            {
                e.CellStyle.BackColor = Color.LightSkyBlue;
            }

            else if (Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString()) >= Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value.ToString()) &&
            Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString()) <= Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value.ToString()))
            {
                e.CellStyle.BackColor = Color.LightSkyBlue;
            }

            else if (Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value) < Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value) ||
                Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value) > Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value))
            {
                e.CellStyle.BackColor = Color.LightSalmon;
            }
        }

这个 CellFormatting 是正确的事件还是我可以使用另一个事件来解决这个问题并在输入结果值并将其与下限值和上限值进行比较后更改行颜色?

标签: c#

解决方案


由于某种原因,问题是您的值之一不是 int,请尝试此代码

private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dgvResult.Rows[e.RowIndex].Cells["Result"].Value == DBNull.Value)
    {
        e.CellStyle.BackColor = Color.LightSkyBlue;
    }
    else
    {
        int cellValue = 0;
        int lowerLimit = 0;
        int upperLimit = 0;
        if (int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString(), out cellValue) 
            && int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value.ToString(), out lowerLimit)
            && int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value.ToString(), out upperLimit)
            )
        {
            if(cellValue >= lowerLimit && cellValue <= upperLimit)
                e.CellStyle.BackColor = Color.LightSkyBlue;
            else
                e.CellStyle.BackColor = Color.LightSalmon;
        }
        else
        {
            // The cell value is not an int..
            e.CellStyle.BackColor = Color.LightSalmon;
        }
    }
}

在“//单元格值不是整数..”之后的行上放置一个断点,然后查看您正在使用的单元格中的值。


推荐阅读