【问题标题】:DataGridView acting weird... not redrawing leaving weird artifacts behindDataGridView 表现得很奇怪......不重绘留下奇怪的工件
【发布时间】:2014-01-30 16:42:14
【问题描述】:

我有使用 DataGridView 的 WinForms 应用程序。我有一个单元格的背景/文本颜色根据另一个单元格(在同一行中)的值而变化。我似乎遇到了问题,当屏幕大小、移动或其他情况时,单元格看起来像垃圾。

这就是问题的样子:

这是我用来更改列颜色的代码。

public static void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // this is used to colorize the cells..
    try
    {
        DataGridView dgv = (DataGridView)sender;

        string currentColumnName = dgv[e.ColumnIndex, e.RowIndex].OwningColumn.Name;

        if (dgv.Columns.Contains(currentColumnName + "_TEXT_COLR"))
        {
            string colourString = dgv[currentColumnName + "_TEXT_COLR", e.RowIndex].Value.ToString();
            e.CellStyle.ForeColor = ColorTranslator.FromHtml(colourString);
        }
        else
            e.CellStyle.ForeColor = Color.Black;

        if (dgv.Columns.Contains(currentColumnName + "_BACK_COLR"))
        {
            string colourString = dgv[currentColumnName + "_BACK_COLR", e.RowIndex].Value.ToString();
            e.CellStyle.BackColor = ColorTranslator.FromHtml(colourString);
        }
        else
        {
            if (dgv.Columns[e.ColumnIndex].ReadOnly)
                e.CellStyle.BackColor = Color.Yellow;
            else
                e.CellStyle.BackColor = Color.White;
        }                

    }
    catch (Exception)
    {
        // ?
    }

}

我已经尝试刷新控件和表单...没有运气。

有人吗?

【问题讨论】:

  • 你尝试了什么?在网格上调用Invalidate()?如果必须是立即,甚至可能是Refresh()
  • 是的,我在包含表单的 ResizeEnd 事件上尝试了这两种方法,没有做任何事情。
  • 尝试摆脱 Try...Catch 然后修复你的 null 问题。

标签: c# winforms datagridview


【解决方案1】:

来自here

public static void DoubleBuffered(this DataGridView dgv, bool setting)
{
    Type dgvType = dgv.GetType();
    PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
    pi.SetValue(dgv, setting, null);
}

效果很好!!

【讨论】:

  • DoubleBuffered 通常是一个属性...你不能在适当的构造函数中设置它,甚至在设计器中设置它吗?
  • @DonBoitnott 仅在表单上。它受到保护,因此您要么继承它,要么使用反射。
  • @LarsTech 不正确。该属性是从Control 传下来的。例如,您可以通过Panel 访问它。
  • @DonBoitnott 我第一次以这种方式设置属性。另一个例子是:stackoverflow.com/questions/118528/…
  • @DonBoitnott 不,你不能。在 Control 源代码中是 protected virtual bool
猜你喜欢
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2014-12-12
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多