Search code examples
c#wpfdatagridstring-formattingimport-csv

C# WPF - Formatting a datagrid after importing from csv


I have imported a csv datatable and all columns are formatted as strings. Is there a way to change the format column values to short date or currency after it has been imported? Any help is appreciated.


Solution

  • You can do this with StringFormat

     <DataGrid x:Name="MyData" VerticalAlignment="Top" Margin="2,2,3,0" ItemsSource="{Binding Items}" HeadersVisibility="Column" AutoGenerateColumns="False" CanUserDeleteRows="False">
          <DataGrid.Columns>
                <DataGridTextColumn Header="Date" Width="auto" Binding="{Binding Date, StringFormat=M/d/yyyy}"/>
                <DataGridTextColumn Header="Price" Width="auto" Binding="{Binding Price, StringFormat=C}"/>
          </DataGrid.Columns>
     </DataGrid>
    

    You can check out the string format class https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.7.2