Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've read a lot about column format of WPF DataGrid but couldn't find a solution for number format. What I have so far is a SQLite database and some lines of code that works fine - except number format. What I want is 2 numbers after the decimal point.

...
DataGrid1.Columns.Clear();
DataGrid1.AutoGenerateColumns = false;
Binding bindAmount = new Binding("amount");
CultureInfo germanCulture = CultureInfo.CreateSpecificCulture("de-DE");
bindAmount.ConverterCulture = germanCulture;
DataGridTextColumn colAmount = new DataGridTextColumn();
colAmount.Header = "amount";
colAmount.Binding = bindAmount;
style = new Style();
style.TargetType = typeof(DataGridCell);
se = new Setter();
se.Property = ContentStringFormatProperty;  // these 2 lines
se.Value = "0.00";                          //   don't work !!!
style.Setters.Add(se);
se = new Setter();
se.Property = HorizontalAlignmentProperty;
se.Value = HorizontalAlignment.Right;
style.Setters.Add(se);
colAmount.CellStyle = style;
colAmount.Width = 70;
DataGrid1.Columns.Add(colAmount);
DataGrid1.ItemsSource = dbDataTbl.DefaultView;
...

Why I don't do it with XAML? Because I want different formats for different countries.

What I have tried:

see the above text and code ...
Posted
Updated 10-Jan-23 11:10am
Comments
Graeme_Grant 10-Jan-23 16:46pm    
Why manually code it, why not in XAML??
pitwi 10-Jan-23 17:24pm    
See the last line of my posting: Because I want different formats for different countries.
Graeme_Grant 10-Jan-23 17:27pm    
Again, why are you not using XAML for this?? I have shown you below how easy it is.

1 solution

Using XAML rather than code is a far easier way of working with controls including the DataGrid.

Here is an example of an answer to an older question with a similar question. Create a new project called WpfDataGridDateColumnFormatting and drop this code in:

1. Create a new Model called Widget to hold the data:
C#
public class Widget
{
    public string? Name { get; set; }
    public DateTime? Date { get; set; }
    public int Quantity { get; set; } = 0;
}

2. Add the following code to the MainWindow code-behind:
C#
using System;
using System.Collections.ObjectModel;
using System.Windows;

public partial class MainWindow : Window
{
    private Random random = new();
    public ObservableCollection<Widget> Widgets { get; set; } = new();

    public MainWindow()
    {
        CreateWidgets();
        InitializeComponent();
    }

    private void CreateWidgets()
    {
        for (int i = 0; i < 10; i++)
        {
            Widgets.Add(new()
            {
                Name = $"Widget {i}", 
                Date = DateTime.Now.AddDays(random.NextDouble() * 5),
                Quantity = random.Next(0, 100)
            });
        }
    }
}

3. Now the MainWindow XAML:
XML
<Window x:Class="WpfDataGridDateColumnFormatting.MainWindow"
        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"
        mc:Ignorable="d"
        x:Name="Window"
        Title="MainWindow" Height="450" Width="800">

    <DataGrid DataContext="{Binding ElementName=Window}"
              ItemsSource="{Binding Widgets}"
              AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"
                                Binding="{Binding Name}" />
            <DataGridTextColumn Header="Date"
                                Binding="{Binding Date,
                                          StringFormat={}{0:dd.MM.yy}}" />
            <DataGridTextColumn Header="Quantity"
                                
                                Binding="{Binding Quantity,
                                          StringFormat={}{0:#,##0.00}}">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Setter Property="HorizontalAlignment" Value="Right" />
                    </Style>
                </DataGridTextColumn.ElementStyle>

            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Window>

Now, if you followed the instructions above, and run the app, you will see the last two columns with custom formatting, and the last with number formatting.

As you can see, we are applying the formatting directly on the data binding:
XML
Binding="{Binding Quantity, StringFormat={}{0:#,##0.00}}">

The StringFormat property in the data binding uses the same formatting options as String.Format. (ref: Standard numeric format strings[^])

A great tutorial website for WPF: The complete WPF tutorial - WPF tutorial[^]

Hope this helps!
 
Share this answer
 
Comments
pitwi 12-Jan-23 17:12pm    
Thanks very much Graeme_Grant but because I couldn't get your solution to work I found an alternative solution: I do the string formatting in the SQL query. ;)
Graeme_Grant 12-Jan-23 23:21pm    
The above code is from a working project built specifically to answer your question. If you follow the above instructions above, it will build a working demo app for you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900