【问题标题】:Compare datagridview cell value with image in the DataGridViewImageColumn将 datagridview 单元格值与 DataGridViewImageColumn 中的图像进行比较
【发布时间】:2012-10-03 04:38:29
【问题描述】:

我创建了一个DataGridViewImageColumn,如果图像单元格的值为绿色复选框图像,我想执行操作。 代码如下。但它不在条件内

if (dgvException.Rows[e.RowIndex].Cells["colStock"].Value 
                                              == Properties.Resources.msQuestion)
{
    //Some code
}

请帮忙。

【问题讨论】:

    标签: c# datagridview compare datagridviewcolumn


    【解决方案1】:

    我建议使用单元格标记属性来添加代表图像的文本值 - 例如数字或名称,并使用它来检查显示的图像。 .

    【讨论】:

      【解决方案2】:

      使用相等运算符 (==) 检查图像的相等性不能按照您需要的方式工作。这就是为什么你的平等检查总是返回假。

      您需要确定两个图像的 内容 是否相同 -- 为此,您需要逐像素检查 DGV 单元中的图像和参考图片。我找到了一些指向this article 的链接,这些链接演示了比较两个图像。我把文章中的图片比较算法浓缩成一个方法,以两个Bitmaps为参数进行比较,如果图片相同则返回true:

      private static bool CompareImages(Bitmap image1, Bitmap image2) {
          if (image1.Width == image2.Width && image1.Height == image2.Height) {
              for (int i = 0; i < image1.Width; i++) {
                  for (int j = 0; j < image1.Height; j++) {
                      if (image1.GetPixel(i, j) != image2.GetPixel(i, j)) {
                          return false;
                      }
                  }
              }
              return true;
          } else {
              return false;
          }
      }
      

      (警告:代码未测试)

      使用这种方法你的代码变成:

      if (CompareImages((Bitmap)dgvException.Rows[e.RowIndex].Cells["colStock"].Value, Properties.Resources.msQuestion)) {
          //Some code 
      } 
      

      【讨论】:

      • 非常感谢@Jay Riggs。代码就像一个魅力。非常感谢您的帮助。
      • 小图没问题,大图呢?
      【解决方案3】:

      S.Ponsford 的回答对我来说效果很好,我做了这个通用的例子。 PD:请记住我的第 0 列是我的 DataGridViewImageColumn

      if (this.dataGridView.CurrentRow.Cells[0].Tag == null)
      {                                                    
           this.dataGridView.CurrentRow.Cells[0].Value= Resource.MyResource1;
           this.dataGridView.CurrentRow.Cells[0].Tag = true;                       
      }
      else
      {
           this.dataGridView.CurrentRow.Cells[0].Value = Resources.MyResource2;
           this.dataGridView.CurrentRow.Cells[0].Tag = null;                        
      }                         
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多