c# - 更改单元格值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 是正确的事件还是我可以使用另一个事件来解决这个问题并在输入结果值并将其与下限值和上限值进行比较后更改行颜色?
解决方案
由于某种原因,问题是您的值之一不是 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;
}
}
}
在“//单元格值不是整数..”之后的行上放置一个断点,然后查看您正在使用的单元格中的值。
推荐阅读
- eclipse - Scala 工作表未评估 REPL 并在右侧打印结果
- javascript - 如何在 textContent (JS) 中添加换行符?
- javascript - 无法将 json 数据加载到 D3.JS
- python - Python客户端-服务器套接字错误[Errno 9]错误的文件描述符
- c++ - 为什么 Clang 不喜欢 __DATE__ 宏?
- sql - 用于选择颜色的 SQL 查询不像颜色变体
- javascript - 使用 componentWillmount React.Js 渲染 Json 数据
- reactjs - 为什么反应路由器重定向 nginx 服务器上的所有请求?
- webpack - webpack-dev-server cli --open localhost 在不同的端口
- python - 在 python 中为bloomberg API 安装blpapi 错误