2014-01-28 72 views
0

我现在有很多其他人问过同一个问题并得到答案。但在我的情况下,我似乎无法得到这个工作。我读过几篇文章,建议在每一行上使用DefaultCellStyle。我做了同样的事,但我的颜色不会改变。在DataGridview行中更改颜色C#

这是我的代码:

private void MyHistoryMainControl_Load(object sender, EventArgs e) 
{ 
    editedShipmentGrid.DataSource = handler.GetEditedShipments(); 
    foreach (DataGridViewRow row in editedShipmentGrid.Rows) 
    { 
     if (string.IsNullOrWhiteSpace(row.Cells[54].FormattedValue.ToString())) 
     { 
      row.DefaultCellStyle.ForeColor = Color.Blue; 
     } 

     if (string.IsNullOrWhiteSpace(row.Cells[55].FormattedValue.ToString())) 
     { 
      row.DefaultCellStyle.ForeColor = Color.Red; 
     } 
    } 
} 

我跑在我使用的用户控件的Load方法的代码。数据在DataGridView中正常加载,但颜色不会更改。我也检查了我的状况的布尔价值,它应该改变颜色。我在这里做错了什么?

+0

这应该工作。执行'row.DefaultCellStyle.ForeColor = Color ...'行吗?如果你设置了一个断点,断点实际上是什么? – svinja

+0

是的,他们这样做。是否有一个属性,我必须在DataGridView上设置? – Lahib

+0

你确定你没有重新绑定其他地方的数据源吗? – Plue

回答

0

我找到了解决方案。我不得不在InitializeComponent()后面绑定数据。方法。而在我的Load方法我改变颜色取决于单元格值..

这是解决方案:

public MyHistoryMainControl() 
{ 
    InitializeComponent(); 
    editedShipmentGrid.DataSource = handler.GetEditedShipments(); 
} 

private void MyHistoryMainControl_Load(object sender, EventArgs e) 
{ 
    foreach (DataGridViewRow row in editedShipmentGrid.Rows) 
    { 
     if (string.IsNullOrWhiteSpace(row.Cells[54].FormattedValue.ToString())) 
     { 
      row.DefaultCellStyle.ForeColor = Color.Blue; 
     } 

     if (string.IsNullOrWhiteSpace(row.Cells[55].FormattedValue.ToString())) 
     { 
      row.DefaultCellStyle.ForeColor = Color.Red; 
     } 
    } 
} 
+1

如果您在“DataBindingComplete”事件处理程序中移动颜色更改代码,则不必担心必须设置数据源的位置:) – Junaith

相关问题