C# DataGridView单元格画斜线

功能要求:不符合条件的单元格使用斜线形式表现出来。

1、定义两个变量,一个是存储单元格位置的数组,一个是Graphics 变量

 Graphics gdi; 
 List<DataGridViewCell> pathList = new List<DataGridViewCell>();

2、将要划斜线的单元格都存储起来(注意在添加完单元格后需要添加(this.dataGridView1.focus();))

  pathList.Add(dataGridView1.Rows[i].Cells[inde]);

3、写dataGridview方法中的dataGridView1_CellPainting()方法

   var realList = pathList.Where(a => a.RowIndex >= 0 && a.ColumnIndex >= 0);
   foreach (var obj in realList)
      {
           gdi = e.Graphics; //得到DataGridView的画布
            var size = obj.Size; //单元格大小
             Rectangle rec = this.dataGridView1.GetCellDisplayRectangle(obj.ColumnIndex, obj.RowIndex, false);  //得到单元格对应的坐标,长宽
             //在画布上开画,坐标就是要画的单元格的坐标,而Height/2是画到单元格的中间,长度就是单元格的长度。
             gdi.DrawLine(new Pen(Color.LightGray), new Point(rec.X, rec.Y ), new Point(rec.X + rec.Width, rec.Y + rec.Height));
                   
     }