Text Alignment - Cell Painting
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: Text Alignment - Cell Painting

  1. #1
    Join Date
    Feb 2010

    Text Alignment - Cell Painting

    Hello, I am stuck on a problem that I am hoping that somebody might be able to help me with

    I want to be able to line up a currency symbol on the left hand side of the cell, with a negative sign to the left of the symbol if the cell is a negative, and then have the value on the right hand side of the cell

    Attached is a small screen shot of how the currency sign is showing up.

    Unfortunately, the currency symbol does not line up perfectly. If it has a negative sign then it is a small amount more to the left, you may need to zoom up the picture to see it.

    Any idea how to fix this.
    Depending on the font and size used depends on how much it is askew.

    My code...
    private void TestGrid_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 - e.Graphics.MeasureString("$", e.CellStyle.Font).Width - 1;
                Bounds.X += CharWidth;              
                Bounds.Width -= CharWidth;
                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;
    Attached Images Attached Images  

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)