how can I format numerical values using .NET standard numeric format strings like 'G5'

I need to display my numerical values using the standard numeric format string "G5", in order to be consistent with the rest of my application.

I have looked into using NumberFormatInfo, but here I can only set a fixed number of decimals.

With Microsoft standard DataGrid control, I can do:

col.DefaultCellStyle.Format = "G5";


Is there a way to achieve something similar with SFDataGrid?


Thanks in advance




1 Reply 1 reply marked as answer

MA Mohanram Anbukkarasu Syncfusion Team August 17, 2020 01:26 PM UTC

Hi Arjan, 

Thanks for contacting Syncfusion support.  

SfDataGrid doesn’t have any direct support to achieve this behavior. However you can achieve this by creating a custom renderer for the NumericColumn to restrict the number of digits to be displayed in the cell as shown in the following code example.  

Code example :  

public Form1() 
{ 
    InitializeComponent(); 
    var dataSource = new OrderInfoCollection().OrdersListDetails; 
    sfDataGrid1.DataSource = dataSource; 
    (this.sfDataGrid1.Columns["UnitPrice"] as GridNumericColumn).NumberFormatInfo = new System.Globalization.NumberFormatInfo() { NumberDecimalDigits = 4 }; 
    this.sfDataGrid1.CellRenderers["Numeric"] = new CustomNumericCellRenderer(); 
} 
 
public class CustomNumericCellRenderer : GridNumericCellRenderer 
{ 
    protected override void OnRender(Graphics paint, Rectangle cellRect, string cellValue, CellStyleInfo style, DataColumnBase column, RowColumnIndex rowColumnIndex) 
    { 
        if (column.GridColumn.MappingName=="UnitPrice" && cellValue.Length > 5) 
        { 
            string modifiedValue = string.Empty; 
            var c = 0; 
            foreach (var character in cellValue) 
            { 
                if (c >= 5) 
                { 
                    cellValue = modifiedValue; 
                    break; 
                } 
 
                modifiedValue += character; 
                if (character != '.' && character != ',') 
                    c++; 
            } 
        } 
 
        base.OnRender(paint, cellRect, cellValue, style, column, rowColumnIndex); 
    } 
} 



Please have a look at this sample and let us know if you have any concerns in this.  

Regards, 
Mohanram A. 


Marked as answer
Loader.
Up arrow icon