Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Format Money in a DataGrid with $?

Tags:

c#

.net

I want to format monetary values in my DataGrid so that they start with the dollar sign ($).

How can I do this?

like image 217
Nikki196 Avatar asked Apr 06 '12 14:04

Nikki196


2 Answers

If you're talking about showing the data in a monetary format, or even simply adding a "$" to the beginning of data so that

1.49

displays as

$1.49

then you can do this in several ways. On a DataGrid control (web) you can set the DataFormatString property.

One option is to set it to "c" for Currency on a BoundColumn. This will work if your web server's CultureInfo is set to en-US

<asp:BoundColumn DataField="CurrencyValue" 
                 HeaderText="Price"
                 DataFormatString="{0:c}">

Another option is to use a CustomFormatString, which gives you more refined control over how it's displayed. Say you always want it to be EXACTLY three digits to the right of the decimal and EXACTLY two digits to the left, you can use

{0:$00.000}

More information on custom data format strings for numbers can be found here: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Since you're working in WinForms, (sorry, I just re-read the comments) you would use the same technique but apply it to the column's DefaultCellStyle as shown here: http://msdn.microsoft.com/en-us/library/f9x2790s.aspx

dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
like image 163
David Avatar answered Oct 14 '22 18:10

David


Also if you are looking for a Culture-specific cell formatting with a CultureInfo, you can use the FormatProvider Property of DataGridCellStyle. In WinForms:

dataGridView1.Columns["MoneyValue"].DefaultCellStyle.Format = "c";
dataGridView1.Columns["MoneyValue"].DefaultCellStyle.FormatProvider = 
System.Globalization.CultureInfo.CreateSpecificCulture("es-CO");
like image 2
WhySoSerious Avatar answered Oct 14 '22 18:10

WhySoSerious