更改单元格的背景颜色在 Form 的构造函数中不起作用 [英] Changing the BackColor of a Cell Does't work in Form's Constructor

查看:25
本文介绍了更改单元格的背景颜色在 Form 的构造函数中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码看起来很简单,我不确定我错过了什么......

My code seems pretty straight forward, I'm not sure what I'm missing...

我遍历 dataGridView.Rows 中的每一行,然后遍历每个单元格并检查它的值是否为 "OK" 然后我将单元格颜色更改为Color.Red 并在控制台中写入 "IF WAS TRUE".

I'm looping through each row in dataGridView.Rows, then looping through each cell and checking if its value is "OK" then I change the cell color to Color.Red and also write "IF WAS TRUE" in console.

我在控制台窗口中有那个漂亮的小 "IF WAS TRUE" 只是为了向自己证明 if 语句被捕获(它是).但是我的单元格颜色保持不变White.

I have that nice little "IF WAS TRUE" in console window just to prove to myself that the if statement is getting caught (it is). But my cell color remains unchanged White.

任何建议将不胜感激!

public partial class Form1 : Form
{
    public static BindingList<Record> record_list = new BindingList<Record> { };
    public static DataGridViewCellStyle style = new DataGridViewCellStyle();
    public Form1()
    {
        InitializeComponent();
        FillData();
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            for (var i = 0; i < row.Cells.Count; i++)
            {
                Console.WriteLine(row.Cells[i].Value);
                if (row.Cells[i].Value as string == "OK")
                {
                    row.Cells[i].Style.BackColor = Color.Red;
                    Console.WriteLine("IF WAS TRUE");
                }
            }
        }
    }
    void FillData()
    {
        record_list.Add(new Record("Support-19", "TEST", 0, 0.0, "", 
            "LOC CODE2", 0.0, 0, 0, 0.0, ""));
        record_list.Add(new Record("Support-99", "ROBOTS", 0, 0.0, "",
            "OK", 0.0, 0, 0, 0.0, ""));
        record_list.Add(new Record("Support-27", "TEST2", 0, 0.0, "", 
            "LOC CODE1", 0.0, 0, 0, 0.0, ""));
        dataGridView.DataSource = record_list;
    }
}

public class Record
{
    public string Station { get; set; }
    public string UserName { get; set; }
    public int EvtActive { get; set; }
    public double EvtTime { get; set; }
    public string EvtTimeString { get; set; }
    public string LocCode { get; set; }
    public double LastLoop { get; set; }
    public int CompLvl { get; set; }
    public int RecordID { get; set; }
    public double ConnectTime { get; set; }
    public string Notes { get; set; }

    public Record(string a, string b, int c, double d, string e,
        string f, double g, int h, int i, double j, string k)
    {
        this.Station = a;
        this.UserName = b;
        this.EvtActive = c;
        this.EvtTime = d;
        this.EvtTimeString = e;
        this.LocCode = f;
        this.LastLoop = g;
        this.CompLvl = h;
        this.RecordID = i;
        this.ConnectTime = j;
        this.Notes = k;
    }
}

这被标记为重复,但这对我来说似乎不同.在另一个 SO 帖子中,看起来像一个单元格被直接发送到一个函数,因为我正在迭代单元格.我尝试以类似的方式调用 BackColor 属性,但没有得到任何结果...

This was marked as duplicate, but this seems different to me. In the other SO post, it looks like a cell is being sent to a function directly where as I am iterating over cells. I try to call the BackColor property in a similar manner and I get no results...

推荐答案

您在构造函数中对 DataGridView 的单元格和行所做的更改(在表单 Load 事件之前)不会被持久化,它们会丢失.这不仅仅是关于样式,而是关于行和单元格的所有更改.

The changes which you make on cells and rows of DataGridView in constructor (before form Load event) will not be persisted and they will be lost. It's not about just styles, it's about all changes on rows and cells.

实际上你在加载后看到的列和行并不是你在构造函数中看到的.

In fact the columns and rows which you see after load are not those that you see in constructor.

简短的回答(如上所述)是您应该在表单的 Load 事件中初始化样式.为什么?

The short answer (as said) is you should initialize styles in Load event of form. But Why?

为什么您在构造函数中对 DataGridView 的单元格和行所做的更改没有持续存在而丢失了?

Why do changes which you make on cells and rows of DataGridView in constructor don't persist and they lost?

答案是因为DataGridViewOnBindingContextChanged.

当您显示显示 Form 的任务序列的 Form 导致调用这些方法时:CreateControlOnBindingContextChanged.导致每个子控件的OnParentBindingContextChanged被调用,结果所有子控件的OnBindingContextChanged都会被调用.

When you show a Form sequence of tasks that shows a Form cause calling these methods: CreateControlOnBindingContextChanged. Which cause OnParentBindingContextChanged of each child control be called and as a result, OnBindingContextChanged of all child controls will be called.

现在如果你看看 DataGridView.OnBindingContextChanged 你会看到,一个名为 RefreshColumnsAndRows 调用它清除所有行和列并再次添加它们:

Now if you take a look at DataGridView.OnBindingContextChanged you will see, a method named RefreshColumnsAndRows called which clears all rows and columns and add them again:

private void RefreshColumnsAndRows()
{
    this.Rows.ClearInternal(false /*recreateNewRow*/);
    RefreshColumns();
    RefreshRows(true /*scrollIntoView*/);
}

所以你在加载后看到的列和行不是你在构造函数中看到的.它们是新对象.因此,您在构造函数中对行和列所做的更改将不会被持久化.

So the columns and rows which you see after load are not those that you see in constructor. They are new objects. So changes which you made on rows and columns in constructor will not be persisted.

动态改变样式的正确方法是什么?

虽然您可以将代码移动到 FormLoad 事件,但更适合动态设置行和单元格样式的位置是使用 CellFormatting 事件DtaGridView

Although you can move your code to Load event of Form but a more suitable place to style rows and cells dynamically is using CellFormatting event of DtaGridView

这篇关于更改单元格的背景颜色在 Form 的构造函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆