【问题标题】:How to clear image in DataGridView image column in C#如何在 C# 中清除 DataGridView 图像列中的图像
【发布时间】:2020-05-18 08:27:25
【问题描述】:

我尝试在 DataGridView 图像列中清除图像。我不知道为什么单元格中的值没有更新。

这个代码当我得到图像时显示成功没有任何问题:

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        var col = e.ColumnIndex;
        var row = e.RowIndex;
        var count = dataGridView1.RowCount; 

        if (col == 4)
        {
            DataGridViewCell cell = dataGridView1.Rows[row].Cells[col]; // insert value column
            DataGridViewCell cell2 = dataGridView1.Rows[row].Cells[3];  // value check column 
            DataGridViewCell cellpic = dataGridView1.Rows[row].Cells[6]; // image column (ok-no)

            if (cell.Value != null)
            {
                string cellval = cell.Value.ToString();
                string cellchk = cell2.Value.ToString();
                if (cellval.Contains(cellchk))
                {
                    Image image = Image.FromFile("D:/ScanChk/img/ok.png");
                    cellpic.Value = image;
                }
                else
                {
                    Image image = Image.FromFile("D:/ScanChk/img/no.png");
                    cellpic.Value = image;
                }
            }
        }
    }

我试图使 null 值,但值不会改变。它仍然显示我之前得到的图像。

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) // Button clear values
    {
        var col = e.ColumnIndex;
        var row = e.RowIndex;

        if (dataGridView1.Columns[col] is DataGridViewButtonColumn)
        {
            dataGridView1.Rows[row].Cells[4].Value = null;
            dataGridView1.Rows[row].Cells[6].Value = null; // image column (ok-no)
        }
    }

为什么图像列不更新为空值?我的代码有什么问题?以及如何清除 DataGridView 图像列中的图像。谢谢。

【问题讨论】:

  • 您可以使用文件流将图像设置为单元格并检查。使用 (FileStream fileStream = File.Open("D:/ScanChk/img/ok.png", FileMode.Open)) { Bitmap bitmap = new Bitmap(fileStream);图像图像=(图像)位图; cellpic.Value = 图像; }
  • 如果您设置[DataGridViewImageCell].Value = null;,它将显示默认的空图像(红十字)。可以通过设置对应的[DataGridViewImageColumn].DefaultCellStyle.NullValue = new Bitmap(1, 1);来防止

标签: c# datagridview datagridviewimagecolumn


【解决方案1】:

试试这个:

((DataGridViewImageCell)dataGridView1.Rows[row].Cells[4]).Value = null;

【讨论】:

  • 欢迎来到stackoverflow。你能详细说明为什么这应该有效吗?
猜你喜欢
  • 2012-01-01
  • 2020-12-18
  • 2011-02-07
  • 2013-05-22
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多