【问题标题】:Reposition the Error Icon of a DataGridView重新定位 DataGridView 的错误图标
【发布时间】:2014-07-03 20:41:11
【问题描述】:

我在数据绑定的 winform 上有一个 datagridview。网格不允许编辑,它只能查看来自两个独立数据源的比较的数据不一致,因此可以在数据的记录应用程序中更正修复。在进行比较时,如果出现问题,我会设置 DataRow 的 SetColumnError 属性。问题是当数据绑定完成并且网格呈现错误图标时覆盖部分 datagridcell 数据。我已经尝试了在 SO 和网络上找到的几种不同的方法,但没有任何方法可以移动图标。有什么想法吗?

我已经在后面的代码中构建网格时设置了以下内容

Padding newpadding = new Padding(10, 0, 30, 0)
datagridview.RowTemplet.DefaultCellStyle.Padding = newPadding

但这就是结果

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    我找到了问题的解决方案。在尝试了许多不同的事情之后,我发现了一段代码here 解决了这个问题。

    这是以前的:

    后面是:

    至少对我来说,可以在CellPainting() 事件中进行更改。我正在将一个 DataSet 数据绑定到一个只读的 DataGridView 中。 DataSet 已包含来自针对 DataSet 运行的内部操作的 Errors 和 ErrorText。

    关键代码更改为e.CellBounds.X + 30,这会将额外的 30 填充到 X 轴,以便将图像推到右侧。

    private void dgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ErrorIcon);
        if (e.ColumnIndex > -1 && e.RowIndex > -1)
        {
            if (this.dgv[e.ColumnIndex, e.RowIndex].ErrorText != string.Empty)
            {
                Rectangle errorRect = this.dgv[e.ColumnIndex, e.RowIndex].ErrorIconBounds;
                errorRect.X += e.CellBounds.X + 30;
                errorRect.Y += e.CellBounds.Y;
                e.Graphics.DrawImage(gridErrorIcon, errorRect);
            }
            e.Handled = true;
        }
    }
    
    internal static Image gridErrorIcon
    {
        get { return Properties.Resources.Error; }
    }
    

    【讨论】:

      【解决方案2】:

      我不知道如何操作错误图标,既不知道它的位置,也不知道其他任何东西。

      但也许这个小解决方法会有所帮助:与其改变它的位置,不如通过清除错误文本来完全删除它。如果您将其复制到工具提示中,您仍然可以访问其值,甚至可以将其显示给用户。

      通过绘制单元格的背景或前景来指示错误,而不是图标。

      通过结合 ValidatingValidated 事件,我让它为我工作,一个设置颜色,另一个清除错误指示器,但颜色仍然存在:

      private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
      {
          DataGridViewCell cell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex];
          cell.ToolTipText = cell.ErrorText;
          cell.ErrorText = "";
      }
      
      private void DGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
      {
          DataGridViewCell cell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex];
          cell.Style.BackColor = cell.ErrorText != "" ? Color.Salmon : datagridview.BackColor;
      
      }
      

      【讨论】:

      • 谢谢@TaW。当我看到图标的问题时,我将其视为一个选项,但我希望 MS 预见到这是一个问题,并包括一种操纵定位的方法。如果我必须走那条路,我可以,但我宁愿找到定位的解决方案。
      猜你喜欢
      • 2010-11-06
      • 1970-01-01
      • 2015-03-22
      • 2017-06-21
      • 2012-03-26
      • 1970-01-01
      • 2010-09-22
      • 2016-03-22
      • 2016-07-20
      相关资源
      最近更新 更多