5
Answers

Graphics.MeasureString - Having trouble with CellPainting with DataGridView

Grant McConville

Grant McConville

13y
5.7k
1
Hello,

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

Answers (5)