【问题标题】:Changing row color in not-active DataGridView更改非活动 DataGridView 中的行颜色
【发布时间】:2011-06-08 10:52:39
【问题描述】:

不活动时,在 DataGridView 中更改某些行的颜色的最佳方法是什么??

在“真实”世界中,我想在单击按钮后使用它来格式化所有 DataGridView 行,具体取决于某些条件。

要重现行为,请尝试:
1. 在 WinForms 应用程序中放置 TabControl 和两个标签页。在第一个选项卡上放置 button,在第二个选项卡上放置 DataGridView
2. 使用以下代码:

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public int counter = 0;

        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Surname", typeof(string));
            dt.Rows.Add("Mark", "Spencer");
            dt.Rows.Add("Mike", "Burke");
            dt.Rows.Add("Louis", "Amstrong");

            dataGridView1.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            counter++;
            this.Text = "Event counter: " + counter.ToString();

            dataGridView1.Rows[1].DefaultCellStyle.BackColor = System.Drawing.Color.Red;
        }
    }
}

我将 counter 变量用于测试不同的选项,以查看颜色变化事件被触发的次数(越少越好;) - 理想情况下只有一次)。

现在,当您第一次单击按钮时没有进入 tabPage2,然后切换到 tabPage2 - 行的颜色不会改变。这是我遇到的问题。

当您首先激活tabPage2,然后然后按下按钮,或者当您以编程方式设置tabControl1.SelectedIndex = 1;,然后颜色行然后切换回@时,它将起作用987654323@ - 但在这种情况下它会“闪烁”。

我还尝试将颜色更改代码放到 cell_painting 事件中,但对我来说这有点过头了 - 即使您将鼠标移到 datagridview 上,它也会在短时间内触发数百次,而我需要只做一次。

你对如何解决这个问题有什么建议吗?

最好的问候,
马辛

【问题讨论】:

  • @V4Vendetta:作为最后的解决方案 - 是的,但它被解雇了很多次,浪费了我的 CPU 时间;)

标签: c# datagridview


【解决方案1】:

一种可能性是 datagridview 绘制事件中的颜色(当标签页更改时触发)。

private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
}

这对我来说效果很好 - 当您更改选项卡时,绘制事件确实会被调用多次,所以如果您只想设置 DefaultCellStyle 一次,您可以执行以下操作:

public partial class Form1 : Form
{

    private bool setcol;
    private bool painted;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        setcol = true;
        painted = false;
    }

    private void dataGridView1_Paint(object sender, PaintEventArgs e)
    {
        if (setcol && !painted)
        {
            painted = true;
            dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
        }
    }
}

【讨论】:

  • @mj82 整理它的一种方法是将 datagridview 控件子类化,然后将这个逻辑放在那里(可能有一个新属性,您可以在其中设置背景颜色)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
  • 2011-01-12
相关资源
最近更新 更多