格式化datagridview单元格背景不起作用
本文关键字:不起作用 背景 单元格 datagridview 格式化 | 更新日期: 2023-09-27 18:03:23
我有一些代码,应该改变一个datagridview单元格的背景时,该命名单元格的值低于5。
private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("stock"))
{
int intValue = (int)e.Value;
if (intValue <= 5)
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.SelectionBackColor = Color.DarkRed;
e.CellStyle.ForeColor = Color.White;
if (!e.CellStyle.Font.Bold)
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
}
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
}
我得到的错误是:
当您尝试强制转换一个数字时,请确保其值小于infinite。
确保源类型在目标类型
中可转换
我只想检查datagridview单元格中的整数是否大于或小于5。
如果是,请为单元格添加红色背景。
代码有什么问题?我设法使它工作,因为你看到它在datagridview,但是当我试图从codeproject.com打印DGVPrinter类的内容,它失败与上述错误。
什么线索吗?
我得到调用DGVPrinter类的错误位于这一行:
int intValue = (int)e.Value;
谢谢你的帮助。
您的截图清楚地显示e.Value
的值为"pezzi",而不是数字。
如果有可能一些值是数字,而另一些值是非数字(或空白),您应该使用TryParse()
:
int intValue;
if (int.TryParse(e.Value, out intValue) && intValue <= 5)
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.SelectionBackColor = Color.DarkRed;
e.CellStyle.ForeColor = Color.White;
if (!e.CellStyle.Font.Bold)
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
}
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}