This is a migrated thread and some comments may be shown as answers.

How to format a number column

14 Answers 819 Views
GridView
This is a migrated thread and some comments may be shown as answers.
xp
Top achievements
Rank 1
xp asked on 27 Jul 2009, 02:21 PM
I have a number type column (decimal). How can I display formatted number (ex 2 digits after decimal point) in that column ? how to do it in xaml and how to do by code (C#)?

Thanks

14 Answers, 1 is accepted

Sort by
0
Rossen Hristov
Telerik team
answered on 27 Jul 2009, 02:32 PM
Hello sam,

You should use the DataFormatString of the column like this:

<UserControl x:Class="TicketID_226294_RowDetailsCustom.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    xmlns:telerik="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.GridView"  
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    <Grid> 
        <telerik:RadGridView Name="clubsGrid" AutoGenerateColumns="False"
            <telerik:RadGridView.Columns> 
                <telerik:GridViewDataColumn  
                    Header="Price" 
                    DataMemberBinding="{Binding Price}"  
                    DataFormatString="{}{0:F}"
                </telerik:GridViewDataColumn> 
            </telerik:RadGridView.Columns> 
        </telerik:RadGridView> 
    </Grid> 
</UserControl> 
 

The F above is a fixed-point string format, but you can use any standard format as described here.

In C# you should omit the first pair '{}' since this is a special escape sequence for XAML only.

Also, you can check out our Data Formatting example.

I hope this helps.

Best wishes,
Ross
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
xp
Top achievements
Rank 1
answered on 27 Jul 2009, 04:49 PM
Thank you Ross for your quickest reply.
Because our data are dynamically loaded from Database, we do not know column datatype until the DataGrid is loaded. Can we bind a converter to a column after the grid is already loaded. something like this

private serviceClient_GetDataCompletedHandler(DataTable dataTable)
{
   _myGrid.ItemsSource = dataTable;
   initColumnConverter():
}

private void initColumnConverter()
{
  foreach(DataColumn col in _myGrid.Columns)
  {
     if(col.DataType.Equals(typeof(Double?)))
     {
                MyConverter converter= new MyConverter();
                col.DataMemberBinding.Converter = converter;
                col.DataMemberBinding.ConverterParameter = GetMyOwnFormatString():
      }
  }
}


I used lightweight DataTable that copies from a sample codes that showed somewhere in this forum.

I tried it without any error, but the convert function inside MyConverter is never executed, so the data display in double column is not formatted.

Any suggestions.

Thanks in advance.
0
xp
Top achievements
Rank 1
answered on 27 Jul 2009, 05:34 PM
never mind, I figured out and it works now.
0
Kingsley Magnus-Eweka
Top achievements
Rank 1
answered on 25 Aug 2009, 03:00 PM
How do you do this in code without having to create a datacolumn first ? for example i have this code:

 

 

rdgv1.ShowColumnFooters =

 

true;

 

rdgv1.Columns[

 

"Supplier_Name"].Footer = "Total Ref_Spend: ";

 

 

 

 

//rdgv1.Columns["Ref_Spend"].FormatString = "{0:#,###0.00;(#,###0.00);0}"; DataFormatString="{0:F}">

 

 

 

 

 

 

rdgv1.Columns[

 

"Ref_Spend"].DataFormatString = "{0:F}"; //does not work!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

 

 

 

rdgv1.Columns["Ref_Spend"].Footer = txtblkDisplay1.Text;

 

 

 

 

but as you can see i am accessing the particular  column i want by name  through the Columns collection of my radgridview and want to set the its format but i cant, you can usually do something like this in aspnet

can you please put some code up...I mean in c# not in xaml it is quite easy to do in xaml but since i cant seem to access the DataformatString attrib/property in code without creating a new datacolumn, but i dont want to create a new datacolumn i want to access the existing one i have for each of my columns from my bound datasource, how do i do that????

thanks

 

 

0
Pavel Pavlov
Telerik team
answered on 28 Aug 2009, 11:33 AM
Hello Kingsley Magnus-Eweka,


Please try casting an existing column to GridViewDataColumn.  This will give you access to the property.

Something like :
((GridViewDataColumn)this.RadGridView1.Columns[0]).DataFormatString  = ... 



All the best,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Hector
Top achievements
Rank 1
answered on 08 Oct 2009, 08:55 PM

Posted 11 minutes ago (permalink)

Hi, I cannot get the formating to work for me.  I have a string column that I want to format with phone number (123) 345-2323 and here is my code:

gridMultiSelect.Columns.Add(CreateColumn("Phone", "Value"));  
                    GridViewDataColumn gridVDC = (GridViewDataColumn) gridMultiSelect.Columns[0];  
gridVDC.DataFormatString = "{0:##-####-####}";   

Can anyone tell me what I'm doing wrong?  Thanks

-HEctor
0
Hector
Top achievements
Rank 1
answered on 08 Oct 2009, 09:42 PM
I suppose DataFormatString does not work on string type data fields.  I tried changing it once all the data is loaded, but I get an exception saying the the Domain Service does not allow edit.  Here is how I attempted to change it, any other ideas?
void gridMultiSelect_DataLoaded(object sender, EventArgs e)  
        {  
            foreach (GridViewColumn col in gridMultiSelect.Columns)  
            {  
                if (col.Header.ToString().ToUpper() == "PHONE")  
                {  
                    for (int x = 0; x < gridMultiSelect.Items.Count; x++)  
                    {  
                        ValidValue val = (ValidValue)gridMultiSelect.Items[x];  
                        Int64 num = Convert.ToInt64(val.Value);  
                        val.Value = String.Format("{0:(###) ###-####}", num);  
                    }  
                }  
            }  
        } 

0
Pavel Pavlov
Telerik team
answered on 09 Oct 2009, 10:43 AM

Hi Hector,

I would highly recommend to store numeric values in numeric data types such as Int.

If for some reason that is not applicable to your project  there is still a solution. Please use your custom IValueConverter for the Columns DataMemberBinding .

In the convert method of your custom value converter you may place the logic to translate the string to a formatted number.

In case you have troubles with this implementation just let me know, I will be glad to provide a sample.

Kind regards,

Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Hector
Top achievements
Rank 1
answered on 09 Oct 2009, 12:55 PM
In deed, Pavlov, this is the solution I found in one of your samples.  Thank you. 

void gridMultiSelect_DataLoaded(object sender, EventArgs e)  
        {  
            for (int x = 0; x < gridMultiSelect.Columns.Count; x++)  
            {  
                if (gridMultiSelect.Columns[x].Header.ToString().ToUpper() == "PHONE")  
                {  
                    GridViewDataColumn gridVDC = (GridViewDataColumn)gridMultiSelect.Columns[x];  
                    gridVDC.DataMemberBinding.Converter = new PhoneDataConverter();  
                    gridVDC.Width = new GridLength(100);  
                }  
            }  
        } 

The converter:
public class PhoneDataConverter : IValueConverter  
    {  
         
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
            {  
                Int64 num;  
                if( Int64.TryParse(value.ToString(), out num))  
                    return String.Format("{0:(###) ###-####}", num);  
                else  
                    return value.ToString();  
            }  
 
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
            {  
                throw new  NotImplementedException();  
            }  
    } 
0
Sven
Top achievements
Rank 1
answered on 06 Aug 2011, 05:52 PM
Here is the Converter with a convert back in VB:

Imports System
Imports System.Text.RegularExpressions
 
Public Class PhoneDataConverter
    Implements Data.IValueConverter
    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim num As Int64
        If Int64.TryParse(value.ToString(), num) Then
            Return [String].Format("{0:(###) ###-####}", num)
        Else
            Return value.ToString()
        End If
    End Function
 
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Dim newvalue = Regex.Replace(value, "[- )(]", String.Empty)
        Return newvalue
    End Function
End Class
0
Nilesh
Top achievements
Rank 1
answered on 30 Sep 2015, 12:15 PM

Telerik silverlight datagrid remove leading zero during export like "0001"  exported as "1" 

Is  there any solution for this?

0
Hector
Top achievements
Rank 1
answered on 30 Sep 2015, 12:52 PM

Did the IValueConverter not work for you?  Use the example shown, but instead of returning a string format, return an int.  This has been over six years, so I can't remember the exact solution, but I did use the IValueCovnerter.

0
Joel Palmer
Top achievements
Rank 2
answered on 05 Apr 2016, 05:10 PM
Have any of the more modern versions fixed this?  Also, is there a XAML solution instead of doing this in code behind?
0
Stefan
Telerik team
answered on 08 Apr 2016, 11:04 AM
Hi Joel,

As suggested in a previous reply by my colleague, the built-in mechanism for formatting a column through XAML is by using the DataFormatString property.  Can you please share your obstacles to using it, or I am missing something?

Regards,
Stefan X1
Telerik
Do you need help with upgrading your AJAX, WPF or WinForms project? Check the Telerik API Analyzer and share your thoughts.
Tags
GridView
Asked by
xp
Top achievements
Rank 1
Answers by
Rossen Hristov
Telerik team
xp
Top achievements
Rank 1
Kingsley Magnus-Eweka
Top achievements
Rank 1
Pavel Pavlov
Telerik team
Hector
Top achievements
Rank 1
Sven
Top achievements
Rank 1
Nilesh
Top achievements
Rank 1
Joel Palmer
Top achievements
Rank 2
Stefan
Telerik team
Share this question
or