Have fun with sci.dog

C# DataGridView设置单元格背景颜色

1、需求:

DataGridView中要把用户输入的数据标成黄色,提示这些格子用户需要自行输入数据

2、实现:

绑定DataGridView的CellFormatting事件

由于用户的模板是excel,为了简单,用List嵌套表示行列,第一层是列,第二层是行。标号是背景为黄色的单元格行数。

this.dgvMid.CellFormatting += this.DrawFristMidColor;

private void DrawFristMidColor(object sender,object e)
        {
            DataGridView dgv = sender as DataGridView;
            // 设置用户输入的单元格的背景颜色
            List<List<int>> bpos = new List<List<int>>
            {
                new List<int>(),
                new List<int>(),
                new List<int>(),
                new List<int>(),
                new List<int>(),
                new List<int>(),
                new List<int>(),
                new List<int> { 3, 4, 5, 16, 36, 58, 80, 83, 85, 89, 92, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113 },
                new List<int>()
            };
            var tem = new List<int>();
            for (int i = 3; i <= 117; i++)
            {
                switch (i)
                {
                    case 18:
                    case 34:
                    case 40:
                    case 72:
                    case 86:
                    case 93:
                    case 96:
                    case 116:
                        break;
                    default:
                        tem.Add(i);
                        break;
                }
            }
            bpos.Add(tem);
            bpos.Add(tem);
            bpos.Add(tem);
            bpos.Add(tem);

            for (int col = 0; col < bpos.Count; col++)
            {
                for (int row = 0; row < bpos[col].Count; row++)
                {
                    dgv.Rows[bpos[col][row]-2].Cells[col].Style.BackColor = Color.Yellow;
               
                }
            }
        }

实现结果

还可以参考一个视频

/

赞(0)
未经允许不得转载:SciDog » C# DataGridView设置单元格背景颜色

评论 抢沙发