FormatText of a cell in a DataGrid based on its content

Hi there.

I have a Datagrid with columns that display DateTime values in the "0:HH:mm" format. If the value from the database is "2024-04-01 00:00:00", I want to display just nothing in the respective cell, not "00:00". How do I achieve that?

I tried CellRender:

protected void DataGrid0CellRender(Radzen.DataGridCellRenderEventArgs<ABschein.Models.ArbeitsscheinDB.Dienstplan> args)
        {
            string cell_content = args.Data.d_beginn.ToString();
            if (cell_content.Contains("00:00:00"))
            {
                args.Attributes.Add("FormatString", " ");
            }
        }

with no avail. And I tried a Template:

        <RadzenDataGridColumn TItem="ABschein.Models.ArbeitsscheinDB.Dienstplan" Property="d_beginn" Title="@L["DataGridColumn0.Title"]"  Width="80px">
            <Template Context="data">
                @if ((data.d_beginn.ToString()).Contains("00:00:00"))
                    {
                        <div asp-for="DateTime" asp-format=" ">@data.d_beginn</div>
                        <span style='color:red'>@data.d_beginn</span>
                    }
            </Template>
        </RadzenDataGridColumn>

which adds the same value that exists colored red and unformatted. I tried it with coloring just to see if the criteria is met.

Thanks for your help in advance.

This is definitely not the way to format DateTime. You should either set FormatString of the column or when using Template string.Format with desired format:

Thank you for your quick reply. As I said, I want to format the cell based on the value. Hence, setting FormatString to "{0:HH:mm}" for the entire column would show "00:00" in all cells where there is no "real" value.

I tried to apply your Template to my page in the following way, but it leaves every cell of the column empty:

image

my new code:

           <Template Context="data">
                @if ((data.d_beginn.ToString()).Contains("00:00:00"))
                    {
                        string.Format(" ", data.d_beginn);
                    } else {
                        string.Format("{0:HH:mm}", data.d_beginn);
                    }
            </Template>

Again, what did I do wrong?

You should add @ to actually output text in Blazor:

@(string.Format(" ", data.d_beginn))
1 Like

Thanks korchev,

that did the trick!