Laden...

DGV-Zellen abhängig von den Daten colorieren

Erstellt von ErfinderDesRades vor 14 Jahren Letzter Beitrag vor 14 Jahren 3.732 Views
ErfinderDesRades Themenstarter:in
5.299 Beiträge seit 2008
vor 14 Jahren
DGV-Zellen abhängig von den Daten colorieren

Kleines Sample, wie DGV-Zellen abhängig von den Daten coloriert werden können.

Das CellPainting-Event ist dabei m.E. dem Setzen der CellBackColor vorzuziehen, weil so die Darstellung immer aktuell ist, selbst wenn die DataSource neu befüllt wird, oder Werte per Code geändert werden.


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DGVColoredCells {
   public partial class Form1 : Form {

      private const DataGridViewPaintParts _UserPaintParts = 
         DataGridViewPaintParts.Background | DataGridViewPaintParts.ContentBackground;

      //to colorize Background, selected Background
      private Brush[] _UserBrushes = new Brush[]   { Brushes.Yellow, Brushes.Blue };   

      public Form1() {
         InitializeComponent();
         //switch all BindingSource-DataSources from local Dataset to DataModel-Dataset
         //DataModel-Dataset was already filled in Program.cs, so don't wonder
         this.personBindingSource.DataSource = DataModel.Instance.MyDataSet;
         this.personDataGridView.CellPainting += personDataGridView_CellPainting;
      }

      /// <summary> userdefined painting the 3rd Column, if the Phone-Property >= 1193 </summary>
      void personDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
         DataGridView dgv = (DataGridView)sender;
         if (e.RowIndex < 0 || e.RowIndex >= dgv.RowCount-1 || e.ColumnIndex !=2) return;
         var rwCurrent = (MyDataSet.PersonRow)((DataRowView)dgv.Rows[e.RowIndex].DataBoundItem).Row;
         if(int.Parse( rwCurrent.Phone)<1193) return;
         var pp = e.PaintParts;
         if ((pp & _UserPaintParts) == DataGridViewPaintParts.None) return;
         var selectIndex = (e.State & DataGridViewElementStates.Selected) > 0 ? 1 : 0;
         e.Graphics.FillRectangle(_UserBrushes[selectIndex], e.CellBounds);
         pp = pp ^ _UserPaintParts;
         e.Paint(e.CellBounds, pp);  //let DGV paint all the other PaintParts itselve
         e.Handled = true;
      }
   }
}


Schlagwörter: <Datagridview, ownerdrawing, CellPainting, databinding>

Der frühe Apfel fängt den Wurm.