在DataGridView中更改某些单元格的样式 [英] Changing style of certain cells in DataGridView
问题描述
我正在尝试更改DataGridView中某些单元格的颜色,具体取决于其值与其他单元格相同。可悲的是,这不行。这是我认为应该工作的代码:
I'm trying to change the color of certain cells in a DataGridView depending on wether the value is the same as in other cells. Sadly though, it's not working. This is the code which I thought should work:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 1; j < 8; j++)
for (int k = 8; k < 20; k++)
if (dataGridView2.Rows[i].Cells[j].Value == dataGridView2.Rows[i].Cells[k].Value)
dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Green;
}
dataGridView2.Refresh();
所有列都使用typeof(int)创建,因此不应该是类型问题。另外调试显示我的程序没有输入if子句,但仍然没有显示更改。
All columns are created with typeof(int) so it shouldn't be a type problem. Also debugging showed my program does enter the if-clause, yet still it doesn't display the changes.
提前感谢任何帮助。
推荐答案
我在其中一个应用程序中执行此操作。接近我可以看到,最好的方法是覆盖DataGridView.CellFormatting事件。
I am doing this in one of the apps I work on. Near as I can figure, the best way to do it is to override the DataGridView.CellFormatting event.
在我的应用程序中,每行上有四个布尔属性数据源,我想为每个属性添加一个彩色框,这是true。
In my app, there are four boolean properties on each row of the datasource, I want to add a colored box for each of the properties that is true.
void uxGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
var item = uxGrid.Rows[e.RowIndex].DataBoundItem as NiftyThing;
if(item != null)
{
if(item.Property1)
{
e.CellStyle.SelectedBackColor = e.CellStyle.BackColor = Color.Red;
//Don't display 'True' or 'False'
e.Value = string.Empty;
}
else if(item.Property2)
...
}
}
catch { }
}
我希望有帮助!
这篇关于在DataGridView中更改某些单元格的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!