[GridViewDateTimeColumn FormatString] throwing error

When using the following two columns in a bp:GridView, the first works but the second causes an error.

<bp:GridViewDateTimeColumn Value="{value: BirthDate}"
                           FormatString="MM/dd/yyyy"
                           HeaderText="Birthdate"
                           AllowFiltering="true" />

<bp:GridViewDateTimeColumn Value="{value: BirthDate}"
                           FormatString="{resource: _root.DateFormatString}"
                           HeaderText="Birthdate"
                           AllowFiltering="true" />

The DateFormatString property is defined in the page’s view model as follows:

public string DateFormatString { get; set; } = "MM/dd/yyyy";

The following error is the result:

How do we set the format string for a date column at runtime instead of hardcoded in a page?

Note that a resource is okay as the format is not going to change while the page is open, but it won’t be the same for all users so a hard coded value (like the first example) is not viable.

What you are doing is correct, the Grid is just buggy. I guess a workaround until we fix it would be to find the GridColumn in the viewmodel and set the FormatString property

var grid = (BP.GridView)Context.View.FindControlByClientId("IDOfTheGrid"); // or GetAllDescendants if you want something else than ID
var column = grid.Columns.Single(c => c.HeaderText == "Birthdate");
column.FormatString = this.DateFormatString;

Also note that the FormatString supports the .NET single letter formats which automatically respect the current culture: Standard date and time format strings - .NET | Microsoft Learn, if that’s what you need. "MM/dd/yyyy" is equivalent to "d"

1 Like