无法在datagridview中更改单元格颜色

时间:2011-08-31 11:51:40

标签: c# datagridview

我有一个简单的表单,其中datagridview显示ms sql表中的值。 我希望名称“dc”的列中超过400的值变为红色(FONT IN RED)。 我一遍又一遍地尝试过但我无法完成它。这是代码:

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
    int cellval = Convert.ToInt32(row.Cells["dc"].Value);
    if (cellval > 400)
    {
        row.DefaultCellStyle.BackColor = Color.Red;
        MessageBox.Show("O valor da célula é " + cellval, "WLic2010", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

最有趣的是,MessageBox的内容确实证明了它理解我的请求,因为它只会弹出超过400的值。

请帮助!!

5 个答案:

答案 0 :(得分:3)

您正在设置行的样式,而不是单元格(DataGridViewCell)。

row.Cells["dc"].Style.BackColor = Color.Red;

答案 1 :(得分:1)

试试这个:

使用“样式”属性 - >

DataGridView1.Item(ColumnIndex, RowIndex).Style.BackColor = Color
DataGridView1.Item(ColumnIndex, RowIndex).Style.ForeColor = Color

DataGridView1.CurrentCell.Style.BackColor = Color
DataGridView1.CurrentCell.Style.ForeColor = Color

希望这能回答你的问题。

答案 2 :(得分:0)

您是否尝试过使用CellFormatting事件,可以检查当前单元格的值,然后更改BackColor

答案 3 :(得分:0)

要交换字体颜色,您需要更改ForeColor属性,尝试这样:

row.Cells["dc"].Style.ForeColor = Color.Red;

答案 4 :(得分:-1)

如果您使用DataGridViewCell.Style.ForeColor而不是DefaultCellStyle.BackColor,则应该解决这个问题。

相关问题