I am trying to display a column in a datagridview, so that it looks like the currency format in excel.
By this, I mean that the currency sign or symbol ("$") is in the same place, on the left hand sign in each cell, but if the cell value is negative then it will have a negative sign in front, and then the value following this but on the right hand side of the cell.
My problem is that I cannot figure out how to line up the symbol.
This is the code I have written so far
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
Decimal Value;
String Symbol;
RectangleF Bounds;
StringFormat Format;
if (e.ColumnIndex == 1 && e.RowIndex >= 0 && e.Value != null)
{
e.PaintBackground(e.ClipBounds, true);
Value = Convert.ToDecimal(e.Value);
Format = new StringFormat();
Format.Alignment = StringAlignment.Near;
Format.FormatFlags = StringFormatFlags.NoWrap;
Bounds = e.CellBounds;
if (Value >= 0)
{
Symbol = "$";
float CharWidth = e.Graphics.MeasureString("-", e.CellStyle.Font).Width; // Make a space where the negative sign would be
Bounds.X += CharWidth;
Bounds.Width -= CharWidth;
}
else
{
Symbol = "-$";
Value = 0 - Value;
}
e.Graphics.DrawString(Symbol, e.CellStyle.Font, new SolidBrush(e.CellStyle.ForeColor), Bounds, Format);
Bounds.X += Bounds.Width;
Bounds.Width = e.CellBounds.Width - (Bounds.X - e.CellBounds.X);
if (Bounds.Width >= 0)
e.Graphics.DrawString(Value.ToString(), e.CellStyle.Font, new SolidBrush(e.CellStyle.ForeColor), Bounds, Format);
e.Handled = true;
}
}
Unfortunatly the measure string gives a larger result than expected, almost like it has a space after it
Any ideas as to how to get it around this?
Thanks
Unfortunatly the measure string gives a larger result than expected, almost like it has a space after it
Any ideas as to how to get it around this?
Thanks
Grant McConvillePosted Jun 7, 2011, 4:06 PM
eg
-$ 1,403.25
$ 25.62
-$ 128.32
Suthish NairPosted Jun 7, 2011, 7:01 AM
Grant McConvillePosted Jun 7, 2011, 3:11 AM
float CharWidth = e.Graphics.MeasureString("-", e.CellStyle.Font).Width; // Make a space where the negative sign would be
with this one
float CharWidth = e.Graphics.MeasureString("-$", e.CellStyle.Font).Width - e.Graphics.MeasureString("$", e.CellStyle.Font).Width
However, this does not line either.
I'm a little bit stumped as to why this does not work
Grant McConvillePosted Jun 6, 2011, 4:14 PM
Suthish NairPosted Jun 6, 2011, 5:56 AM