简体   繁体   中英

How to change the Numeric seperator in DataGrid?

I have an query with number format.When changed the decimal separator(.) ---> (,) by using Region settings, type the (1.5) in excel sheet it will changed as (1,5) correctly.
My problem is in DataGridView control, I followed the same procedure in DataGrid , but it displayed (1.5) ---> (15). The (,) operator has removed. I need to know, is this the actual behaviour of the DataGrid. Can we perform same like as excel? I have tried below code.

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

CultureInfo culture = CultureInfo.CurrentUICulture;
culture.NumberFormat.NumberDecimalSeparator = ",";
culture.NumberFormat.NumberGroupSeparator = ".";

Please refer comparison image of excel and DataGrid 在此处输入图片说明

Please any one suggest me how to achieve this like excel???

I see a few problems.

  1. You need to set your decimal and group separator strings on the NumberFormat object for the CurrentCulture , not the CurrentUICulture .
  2. You need to ensure that the underlying type to which you are binding that data grid column is a floating point type, such as decimal . I suspect that currently it is an integral type, such as int .

To apply a custom number format to the column, you should perform these settings:

  • To set number format for a column to show thousand separator and define number of digits after decimal point (for example 2 digits), you should assign "N2" to DefaultCellStyle.Format property of the Column .

  • To use a custom thousand separator character and a custom decimal point character, you should create a CultureInfo based on a culture for example "en-US" and then change its NumberFormat.NumberDecimalSeparator and NumberFormat.NumberGroupSeparator and set the culture as DefaultCellStyle.FormatProvider of the Column .

  • Also if the column is a bound column, set its ValyeType to a numeric type. And if it's a bound column, make sure the underlying column in database has one of above types.

Example

Below code adds an unbound column to a grid and use a format for the column with title "Column One" which it shows 1234567.89 like 1.234.567,89 . It uses "." as thousand separator and "," as decimal point:

this.dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
{
    ValueType = typeof(double),
    Name = "Column1",
    HeaderText = "Column One"
});
var culture= CultureInfo.CreateSpecificCulture("en-US");
culture.NumberFormat.NumberDecimalSeparator=",";
culture.NumberFormat.NumberGroupSeparator=".";
this.dataGridView1.Columns["Column1"].DefaultCellStyle.FormatProvider = culture;
this.dataGridView1.Columns["Column1"].DefaultCellStyle.Format = "N2";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM