Search code examples
c#wpfwpfdatagridexceldatareader

Change only choosen columns to a custom format while remaining all columns stay intact in WPF DataGrid?


Edit: I tried the StringFormat, it's working fine but the DataGrid showing only those columns that I've included in <DataGrid.Columns> Actually only VALUE and DATE should be formatted, remaining columns should stay intact. Means now I've to manually write DataGridTextColumn for each and every column? ( I have like 20+ columns, which can be tedious work!)

New to C# here. I have a DataGrid, which gets it's values from a DataTable. I use ExcelDataReader to import from Excel to DataSet and eventually convert it to DataTable.

• How can I change the format of column DATE to system's default format? (There will be different date format in different systems)
• How can I change the format of column VALUE to exactly 2 decimal places?

In VB.NET, It was simple : DataGridView1.Columns(6).DefaultCellStyle.Format = "N2"

I cannot seem to get that work here. Please suggest me the best way to change those specific columns to the formats mentioned about. (without Performance degradation, saw some posts involving loops and converters)


Solution

  • You could handle the AutoGeneratingColumn event:

    private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "VALUE":
                e.Column = new DataGridTextColumn
                {
                    Header = e.PropertyName,
                    Binding = new Binding(e.PropertyName)
                    {
                        StringFormat = "N2"
                    }
                };
                break;
            case "DATE":
                e.Column = new DataGridTextColumn
                {
                    Header = e.PropertyName,
                    Binding = new Binding(e.PropertyName)
                    {
                        StringFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern
                    }
                };
                break;
        }
    }