2009-11-24 81 views

回答

2
foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    if (row.Cells[0].Value.ToString() == "someVal") 
    { 
     row.DefaultCellStyle.BackColor = Color.Tomato; 
    } 
} 
+0

谢谢u.I'm刚刚分配datasource.So,这段代码也应包括分配数据源后。对? – Nila 2009-11-24 11:54:56

+0

是的,你应该在分配数据源之后执行此操作 – 2009-11-24 12:07:47

0

设置默认的单元格样式会着色整行。为单个行设置默认值听起来像是一个坏主意。您需要一个else语句来处理那些不属于默认cellstyle设置为“someVal”的行,而不是让它们像其他颜色一样着色,因为它们不采取任何行动。此外,类型转换为Value的实际类型应该会比ToString()提供更好的性能。我可以想象,这可能会在每次更新的整个列表中循环。

相反,只是着色一个单细胞,像这样做:

foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    if ((string)row.Cells[0].Value == "someVal") 
    { 
     row.Cells[0].Style.BackColor= Color.Tomato; 
    } 
} 
1

CellFormatting事件网格可以检查值,它们将被显示,并相应地更改CellStyle

您可以使用事件参数的RowIndexColumnIndex属性来检查要显示哪个单元格。当需要更改属性时,您可以设置CellStyle属性(例如e.CellStyle.ForeColor = Color.Red;)。

0

如果您只想更改当前选定的单元格。

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 

     grid1.CurrentCell.Style.SelectionBackColor = Color.Red; 


    } 
相关问题