简体   繁体   English

彩色datagridview行而不冻结C#

[英]Color datagridview rows without freezing C#

I have a datagridview with 5000 entries. 我有一个5000个条目的datagridview。 And I want to color the rows based on some values. 我想根据一些值为行上色。 Here's how I do it: 我是这样做的:

    foreach (DataGridViewRow row in rows)
    {
        var handlingStage = (ESourceHandlingStage)row.Cells["HandlingStage"].Value;
        switch (handlingStage)
        {
            case ESourceHandlingStage.NotStarted:
                row.DefaultCellStyle.BackColor = UnhandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Given:
                row.DefaultCellStyle.BackColor = GivenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Taken:
                row.DefaultCellStyle.BackColor = TakenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Handled:
                row.DefaultCellStyle.BackColor = HandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Loaded:
                row.DefaultCellStyle.BackColor = LoadedColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            default:
                break;
        }
    }

But when form loads it freezes for a couple of seconds. 但是,当表单加载时,它冻结了几秒钟。 Can can I avoid it? 我可以避免吗?
Thank you for your help! 谢谢您的帮助!

You're looping though all the rows so this will take some time, the more rows you have the more time it will take. 您正在遍历所有行,因此这将花费一些时间,您拥有的行越多,花费的时间就越多。

You could put this processing onto a background thread, but you will need to marshal the code so that the actual change occurs on the UI thread. 您可以将此处理放在后台线程上,但是您需要整理代码,以便在UI线程上进行实际更改。 This would take the same amount of time, but wouldn't lock the UI while it processed. 这将花费相同的时间,但是不会在处理UI时锁定它。

An alternative would be to change the colour as each row is added. 另一种选择是在添加每一行时更改颜色。 However, that does depend on your data being added one row at a time. 但是,这确实取决于您的数据一次被添加一行。

Try to color the row on databinding. 尝试为数据绑定上的行着色。 I think you need to attach to the ItemDataBound event or something similar. 我认为您需要附加到ItemDataBound事件或类似的东西。 Inspect the data and color the row accordingly. 检查数据并相应地为行着色。 That way you don't have to loop over all the rows after they are created but instead you do your job when they are created. 这样,您不必在创建完所有行后就对其进行遍历,而是可以在创建完所有行后进行工作。

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

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