0

I have a DataGridView with AutoGenerateColumns=true.
I populate the data from CSV (so they are all string, not decimal)

DataTable dt = CsvToDataTable(masterlistCsvPath); // My function, returns a DataTable
//dt.Columns['Price'].DataType = Type.GetType("System.Decimal"); // Exception: Cannot change DataType of a column once it has data.
dgvMasterList.DataSource = dt;

How do you format the Price column as currency?
eg. "38.5" → "$38.50" or "38.50"

This doesn't work (it does nothing):

dgvMasterList.Columns["Price"].ValueType = Type.GetType("System.Decimal");
dgvMasterList.Columns["Price"].DefaultCellStyle.Format = "C";

This works (just to prove I'm calling it correctly)

dgvMasterList.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

Another related question:
How do you add a percent symbol to a column?
eg. "5" → "5%"

Aximili
  • 28,626
  • 56
  • 157
  • 216

1 Answers1

0

You could not format string value into currency format. But, you could load schema from the csv into datatable and change the datatype of each field as you want then pass it to your datagridviewcontrol as datasource. Now, you could assign currency format to your price column as "C".

Shell
  • 6,818
  • 11
  • 39
  • 70
  • Thanks Nimesh. I added `dt.Columns['Price'].DataType = Type.GetType("System.Decimal");` but it says *Cannot change DataType of a column once it has data.* – Aximili Mar 30 '14 at 03:27
  • [This](http://stackoverflow.com/questions/9028029/how-to-change-datatype-of-a-datacolumn-in-a-datatable) is how to change the DataType of DataTable Columns – Aximili Mar 31 '14 at 05:24