Data Bars in DataGridView Revised!
Here's a revised version of my "data bars in a DataGridView" code. This one introduces a small margin, and reworks the gradient fill slightly. It also makes the maximum value in the column represent 100% of the width of the data bar, so it's more like Excel 12's version.
First, the code (obviously dataBarColor is a private variable representing the colour of the data bar):
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)
{
Rectangle rect = e.CellBounds;
e.PaintBackground(rect, true);
rect.Offset(-1, 2);
rect.Height -= 5;
double value;
double max = 0;
for (int i = 0; i < dgv.RowCount; i++)
{
value = (double)dgv[e.ColumnIndex, i].Value;
if (value > max) max = value;
}
rect.Width = max == 0 ? 0 : (int)((double)e.Value * rect.Width / max + 1);
if (rect.Width > 0)
{
using (LinearGradientBrush lgb = new LinearGradientBrush(rect,
dataBarColor, e.CellStyle.BackColor, 0.0))
{
Blend blend = new Blend();
blend.Factors = new float[] { 0, 0, 0.8f };
blend.Positions = new float[] { 0.0f, 0.3f, 1.0f };
lgb.Blend = blend;
rect.Offset(1, 0);
rect.Width -= 2;
e.Graphics.FillRectangle(lgb, rect);
}
}
e.PaintContent(e.CellBounds);
e.Handled = true;
}
}
}
And a screenshot:


Comments
# Hairyman
21/03/2006 1:04 PM
the actual graph is better in the other post, i think
# crucible
21/03/2006 1:07 PM
I disagree.
That makes you outvoted I believe :P