C# 格式化datagridview单元格背景不';行不通

C# 格式化datagridview单元格背景不';行不通,c#,.net,datagridview,visual-c#-express-2010,C#,.net,Datagridview,Visual C# Express 2010,我有一些代码,当datagridview单元格中的值小于5时,应该更改该单元格的背景 private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("stock")

我有一些代码,当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;

            }
            
        }
}

感谢您的帮助。

您的屏幕截图清楚地显示
e.value
的值是“pezzi”,而不是数字

如果可能有些值是数字,有些值是非数字(或空白),则应使用
TryParse()

int值;

如果(int.TryParse(e.Value,out-intValue)&&intValue出现此错误时,e.Value的值是多少?请尝试使用int-intValue=int.Parse(e.Value.ToString());谢谢约瑟夫。不幸的是,它甚至不能与您的mod一起工作。@Bayeni e.Value的值正是我所期望的值。我“看到了”数字,整数。我在一个消息框中显示它。显示,我得到的值是3或5,依此类推……我会尝试你的解决方案。无论如何,e.value不是“pezzi”。“pezzi”是我在检查内容之前检查的列的名称,即e.value。我将尝试你的提示。让你知道。好的,它不起作用。这就是TryParse使用的原因(string,out int)并且e.Value不是字符串。调试器声明它是一个对象。所以现在我有点困惑。@Aptivus在您的屏幕截图中,我可以清楚地看到一个显示
e.Value-“pezzi”的小窗口
。我建议您暂停调试器中的代码,并检查可用对象的值。我认为您对对象的值做出了错误的假设。
int intValue = (int)e.Value;
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;
}