C# Can´;t更改datagridview中的单元格颜色
我有一个简单的表单,其中datagridview显示了ms sql表中的值。 我希望名称“dc”列中超过400的值变为红色(红色字体)。 我试了一遍又一遍,但都做不成。代码如下:C# Can´;t更改datagridview中的单元格颜色,c#,datagridview,C#,Datagridview,我有一个简单的表单,其中datagridview显示了ms sql表中的值。 我希望名称“dc”列中超过400的值变为红色(红色字体)。 我试了一遍又一遍,但都做不成。代码如下: foreach (DataGridViewRow row in this.dataGridView1.Rows) { int cellval = Convert.ToInt32(row.Cells["dc"].Value); if (cellval > 400) { row
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的窗口
请帮帮我 试试这个:
使用“样式”属性->
DataGridView1.Item(ColumnIndex, RowIndex).Style.BackColor = Color
DataGridView1.Item(ColumnIndex, RowIndex).Style.ForeColor = Color
或
希望这能回答您的问题。如果您使用DataGridViewCell.Style.ForeColor而不是DefaultCellStyle.BackColor,则应该解决此问题。您设置的是行的样式,而不是单元格(DataGridViewCell)
您是否尝试过使用
CellFormatting
事件,在那里您可以检查当前单元格的值,然后更改背景色
要交换字体颜色,您需要更改前景色
属性,请尝试以下方法:
row.Cells["dc"].Style.ForeColor = Color.Red;
实际上,字体颜色是'ForeColor'DataGridView1.Item不存在DataGridViewCell是类型的名称。参见@stekkie提供的答案;那应该能解决你的问题。嗯。
row.Cells["dc"].Style.BackColor = Color.Red;
row.Cells["dc"].Style.ForeColor = Color.Red;