A lot of people out there will by now have seen the screenshots of Excel 12 (now Excel 2007) and its excellent "data bars". For those that haven't, click here to read about them.

Now, we're working on a little application here that has a form where the user will need to enter a series of 30 percentage values. Seemed like a great use for a grid, and while I was at it I thought I'd try implementing data bars using DataGridView's CellPainting event. Here's my code:

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv.DataSource == null) return; if (e.ColumnIndex == 1 && e.RowIndex >= 0) { if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) { e.PaintBackground(e.CellBounds, true); Rectangle rect = e.CellBounds; rect.Offset(-1, 0); rect.Height--; rect.Width = (int)((float)e.Value * rect.Width / 100 + 1); if (rect.Width > 0) { using (LinearGradientBrush lgb = new LinearGradientBrush(rect, dataBarColor, Color.White, 0.0)) { rect.Offset(1, 0); rect.Width--; e.Graphics.FillRectangle(lgb, rect); } } e.PaintContent(e.CellBounds); e.Handled = true; } } } 

... and here's a screenshot:

Data Bars in a DataGridView