C# DataGridView 行的背景颜色没有改变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9527963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:46:06  来源:igfitidea点击:

DataGridView row's background color is not changing

c#.netwinformsdatagridview

提问by Stardust

I want to change the background color of the DGV's row based on particular condition at load even in Windows Form. But I can't see any change of color to any DGV's row. Could anyone tell me how can I solve this problem?

即使在 Windows 窗体中,我也想根据加载时的特定条件更改 DGV 行的背景颜色。但是我看不到任何 DGV 的行有任何颜色变化。谁能告诉我如何解决这个问题?

private void frmSecondaryPumps_Load(object sender, EventArgs e)
{
            try
            {
                DataTable dt = DeviceData.BindData("SECONDARY_PUMPS".ToUpper());
                dataGridView1.DataSource = dt;

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewColumn column in dataGridView1.Columns)
                    {
                        if (row.Cells[column.Name] != null)
                        {
                            if (row.Cells[column.Name].Value.ToString() == "ON")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Green;

                            if (row.Cells[column.Name].Value.ToString() == "OFF")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                        }
                    }
                }

                dataGridView1.Refresh();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

采纳答案by V4Vendetta

I think the best place would be to set the BackColor in the CellFormattingevent of the DataGridView, something on these lines.

我认为最好的地方是在这些行上设置 BackColor 的CellFormatting事件DataGridView

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index
    // check the cell value under your specific column and then you can toggle your colors
    row.DefaultCellStyle.BackColor = Color.Green;
}

回答by King_Rob

One of the problems with using either the cellformatting, databindingcompleteor even paintevents is that they get fired multiple times. From what I've gathered, there is an issue with the datagridviewcontrol in that you cannot change the color of any of the cells until AFTER the form has been shown. Thus methods that run, or events that fire before Shown()is called will not change the color. The events that are sited as the solution to the problem usually work, but since they're called many times, may not be the most efficient answer.

使用cellformatting,databindingcomplete甚至paint事件的问题之一是它们会被多次触发。从我收集到的信息来看,该datagridview控件存在一个问题,即在显示表单之前您无法更改任何单元格的颜色。因此,在Shown()调用之前运行的方法或触发的事件不会改变颜色。定位为问题解决方案的事件通常有效,但由于它们被多次调用,可能不是最有效的答案。

Probably the simplest solution to the issue is to put your code to fill/color your grids in the Shown()method of your form instead of the constructor. Below is a link to a post in the msdn forums that tipped me off to the solution, it's marked as the answer about 3/4 of the way down the page.

可能最简单的问题解决方案是将您的代码放在Shown()表单的方法中而不是构造函数中来填充/着色您的网格。下面是 msdn 论坛中向我提示解决方案的帖子的链接,它被标记为页面下方约 3/4 处的答案。

MSDN forums post with the Solution

MSDN 论坛发布了解决方案

回答by RRM

Sorry for late answer but I'm just facing exactly the same problem now.

抱歉回复晚了,但我现在正面临完全相同的问题。

I have some general solution for things that don't work properly in the constructor - use a timer

对于在构造函数中无法正常工作的事情,我有一些通用的解决方案 - 使用计时器

Set it for some short time like 100 ms. Then in constructor you will have

将其设置为 100 毫秒等短时间。然后在构造函数中,您将拥有

timer1.Enabled=true

and in timer_Tick event:

在 timer_Tick 事件中:

timer1.Enabled=false

and all the code that doesn't work in constructor goes here...

It worked for me every time.

它每次都对我有用。

回答by Daltons

King_Rob is correct. I had the same issue so I will just post my implementation since the other suggestions here are far from optimal.

King_Rob 是正确的。我有同样的问题,所以我只会发布我的实现,因为这里的其他建议远非最佳。

Add the events handlers (in designer or constructor):

添加事件处理程序(在设计器或构造器中):

this.Load += UserControl_Load; // or form or any control that is parent of the datagridview
dataGridView1.VisibleChanged += DataGridView1_VisibleChanged;

In the load event hander method add a flag

在加载事件处理程序方法中添加一个标志

private bool _firstLoaded;
private void UserControl_Load(object sender, EventArgs e)
{
    _firstLoaded = true;
}

And finally in the visible event handler method:

最后在可见事件处理程序方法中:

private void DataGridView1_VisibleChanged(object sender, EventArgs e)
{
    if (_firstLoaded && dataGridView1.Visible)
    {
        _firstLoaded = false;
        // your code
    }
}

回答by SCG

This code is fast, easy and does not consume memory!

这段代码快速,简单,不消耗内存!

Use this code, for example, inside the CellEndEdit event

例如,在 CellEndEdit 事件中使用此代码

 `try{
 //your code
 }
 catch(Exception){
 //your exception
 }
finally{
yourDataGridView.Visible = false;
 yourDataGridView.Visible = true;
}

`

`

回答by Kaveri

Use the following code to change the Datagrid item color

使用以下代码更改 Datagrid 项目颜色

Datagrid1.SelectedIndex = e.Item.ItemIndex;
Datagrid1.Items[e.Item.ItemIndex].Cells[0].BackColor = System.Drawing.Color.Green;