TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Grant McConville
NA
7
6.4k
Graphics.MeasureString - Having trouble with CellPainting with DataGridView
Jun 6 2011 3:37 AM
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
Reply
Answers (
5
)
Delegates
Access methods declared in interfaces of another project