C# Winform 小技巧(Datagridview某一列按状态显示不同图片)

步骤:

一、导入状态图片到项目中:

二、在窗体中声明一个图片数组,并在窗体的OnLoad事件中加入图片资源:

/// <summary>
/// 存储状态图片序列,避免同一状态对图片重复读取引发闪烁。
/// </summary>
private Image[] StatusImgs;

private void FrmSer_Main_Load(object sender, EventArgs e)
{

StatusImgs = new Image[] { Resources.TaskNA, Resources.TaskPause, Resources.TaskRun, Resources.TaskStart, Resources.TaskStop, Resources.TaskTimer };

}

三、处理Datgridview的格式化事件:

        private void DgvTaskList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (DgvTaskList.Rows[e.RowIndex].IsNewRow) return;
            if (e.ColumnIndex != 0) return;

            string stas =OPString.NZ2Str(DgvTaskList.Rows[e.RowIndex].Cells["RunStatus"].Value);
            if (string.IsNullOrEmpty(stas)) stas = "Timer";
            try
            {
                DataGridViewImageCell tmpCell = (DataGridViewImageCell)DgvTaskList.Rows[e.RowIndex].Cells["StatusImg"];

                switch (stas)
                {
                    case "NA":
                        tmpCell.Value = StatusImgs[0];
                        tmpCell.ToolTipText = "闲置";
                        break;
                    case "Pause":
                        tmpCell.Value = StatusImgs[1];
                        tmpCell.ToolTipText = "暂停";
                        break;
                    case "Run":
                        tmpCell.Value = StatusImgs[2];
                        tmpCell.ToolTipText = "运行中";
                        break;
                    case "Start":
                        tmpCell.Value = StatusImgs[3];
                        tmpCell.ToolTipText = "解析中";
                        break;
                    case "Stop":
                        tmpCell.Value = StatusImgs[4];
                        tmpCell.ToolTipText = "任务终止";
                        break;
                    case "Timer":
                        tmpCell.Value = StatusImgs[5];
                        tmpCell.ToolTipText = "循检中";
                        break;
                    default:
                        tmpCell.ToolTipText = "循检中";
                        break;
                }
            }
            catch (Exception)
            {
            }
        }

  这样,你就能得到一个没有闪烁的状态图片列了。