根据条件更改datagridview单元格颜色 [英] Changing datagridview cell color based on condition
本文介绍了根据条件更改datagridview单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void dataGridView1_DataBindingComplete(object sender,DataGridViewBindingCompleteEventArgs e)
{
if(dataGridView1.Rows.Count> 0&& dataGridView1.Columns.Count> 0)
{
foreach(DataGridViewRow r in dataGridView1.Rows)
{
if(Volume> target value)
{
cell.Style.BackColor = Color.AliceBlue;
}
解决方案
你需要这样做
private void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
foreach(DataGridViewRow Myrow in dataGridView1.Rows )
{//这里2单元格是目标值,1个单元格是Volume
if(Convert.ToInt32(Myrow .Cells [2] .Value)&Convert.ToInt32(Myrow .Cells [1] .Value))//或者你的条件
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
}
同时还要看看单元格格式
I have loaded the data from database to datagridview and have two columns target value and volume where volume >target value that volume cell should be in green color and volume < target value then volume should be in red color. I tried it but I am not able to do it.
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (dataGridView1.Rows.Count > 0 && dataGridView1.Columns.Count > 0)
{
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (Volume > target value)
{
cell.Style.BackColor = Color.AliceBlue;
}
解决方案
You need to do this
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
{ //Here 2 cell is target value and 1 cell is Volume
if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
}
Meanwhile also take a look at Cell Formatting
这篇关于根据条件更改datagridview单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文