C# 更改DataGridview行C中的颜色#

C# 更改DataGridview行C中的颜色#,c#,.net,datagridview,C#,.net,Datagridview,我现在有很多其他人问了同样的问题并得到了答案。但在我的情况下,我似乎无法让这个工作。我读过几篇文章建议在每行使用DefaultCellStyle。我也这么做了,但我认为颜色不会改变 这是我的代码: private void MyHistoryMainControl_Load(object sender, EventArgs e) { editedShipmentGrid.DataSource = handler.GetEditedShipments(); foreach (Dat

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

这是我的代码:

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;
        }
    }
}

我正在使用的UserControl的Load方法中运行此代码。数据在DataGridView中加载良好,但颜色不变。我还检查了我的状况的布尔值,它应该会改变颜色。我做错了什么

我找到了解决办法。我必须在InitializeComponent()之后立即绑定数据;方法在我的加载方法中,我根据单元格值更改颜色

这就是解决方案:

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;
        }
    }
}

这应该行得通。
row.DefaultCellStyle.ForeColor=Color…
行是否实际运行?如果你在他们身上设置了一个断点,断点是否真的命中了?是的,他们命中了。是否必须在DataGridView上设置属性?是否确实没有将数据源重新绑定到其他位置?这是一个新项目。我只有一个方法,这个DataGridView我已经找到了解决方案。谢谢你的帮助。如果您想查看解决方案,我已经回答了我的问题。如果您将颜色更改代码移动到
DataBindingComplete
eventhandler中,您就不用担心数据源的设置:)