[WinForm]- 设置DataGridView单元格内根据不同值显示图片

首先设置要显示图片的列

  DataGridViewImageColumn status = new DataGridViewImageColumn();
            status.DisplayIndex = 0;
            status.HeaderText = "Status";
            status.DataPropertyName = "IsPass";
            status.ImageLayout = DataGridViewImageCellLayout.Zoom;
            dgvTestSteps.Columns.Insert(0, status);

添加DataGridView事件CellFormatting

 dgvTestSteps.CellFormatting += new DataGridViewCellFormattingEventHandler(dgvTestSteps_CellFormatting);

在事件内添加根据数据值显示不同图片的方法,判断列的地方有很多条件可以进行判断,但是通过Index感觉是最不可取的,通过HeadName也会有上下对不上的情况。

  void dgvTestSteps_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvTestSteps.Columns[e.ColumnIndex].HeaderText.Equals("Status"))
            {
                if (e.Value == null)
                {
                    return;
                }              
                StepType type = (StepType)Enum.Parse(typeof(StepType), e.Value.ToString(), true);
                switch (type)
                {
                    case StepType.Success:
                        e.Value = Resources.check;
                        break;
                    case StepType.Fail:
                        e.Value = Resources.close_delete;
                        break;
                    case StepType.Block:
                        e.Value = Resources.attention;
                        break;
                    case StepType.NoRun:
                        e.Value = Resources.green_ball;
                        break;
                }
            }
        }

posted @ 2013-10-21 14:20  NowhereMan  阅读(10744)  评论(1编辑  收藏  举报