Search code examples
c#winformsdatagridviewformatdatagridviewcellstyle

Format string value datagridview c#


I am looking to format a value in a datagridview. These values are a string containing a decimal number. (Like "3000" I want to display it with a thousand separator (space), like this: "3,000".

I know it can be done by assigning format of defaultcellstyle using format like "N2" for example, this works with decimal column type but I'm using a string column type in my datagridview to handle some exception(displaying "-" instead of "0" to simplify users view)

I tried differents cell style format and nothing changed in the display.

do i need to change the column type of my datagridview or it can be done without too much code ?

Thanks for all reply,

Tristan


Solution

  • i just made it working as i expected. i did the commented things first and it just showed errors, so i tried the second way (simpliest) that is not commented.

    string value = cell.Value.ToString();
    //NumberFormatInfo nfi =(NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
    //nfi.NumberGroupSeparator = " ";
    //string formatted = double.Parse(value).ToString("n", nfi);
    //cell.Value = formatted.Replace(".00","");// 12 345.00
    string formatted = double.Parse(value).ToString("# ### ###");
    cell.Value = formatted;