简体   繁体   English

在DataGridview行C#中更改颜色

[英]Changing Color in DataGridview rows C#

I now there are a lot of other people who asked the same question and got an answer. 我现在有很多其他人问同样的问题并得到答案。 but in my case i cant seem to get this to work. 但就我而言,我似乎无法使它正常工作。 I have read a couple of posts that suggests using DefaultCellStyle on each row. 我已经阅读了几篇建议在每行上使用DefaultCellStyle的文章。 I have done the same but i the colors do not change. 我做了同样的事情,但是我的颜色没有改变。

this is my code: 这是我的代码:

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

I am running this code in the Load method of the UserControl i am using. 我正在使用的UserControl的Load方法中运行此代码。 The data loads fine in the DataGridView but the colors do not change. 数据在DataGridView中的加载很好,但是颜色不变。 I also checked the bool value of my condition and it it should change color. 我还检查了我的病情的布尔值,它应该改变颜色。 What am i doing wrong here? 我在这里做错了什么?

I have found the solution. 我找到了解决方案。 I had to bind the data right after the InitializeComponent(); 我必须在InitializeComponent()之后绑定数据。 method. 方法。 And in my Load method i change the colors depending on a cell value.. 在我的加载方法中,我根据单元格值更改颜色。

this is the solution: 这是解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM