0
votes

I'm trying to convert from WinForms to WPF and am struggling a bit with DataGridView -> WPF DataGrid.

I've got all the data loading nicely, just stuck on the cell formatting.

There is a column with numbers, however if the number is zero, rather than show 0, I'd like it to display NIL.

With DataGridView, the below worked

    Private Sub SampleDGV_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles SampleDGV.CellFormatting

    Try
        If e.RowIndex >= 0 And e.ColumnIndex = SampleDGV.Columns(CostColumn.Name).Index Then
            If CDec(e.Value.ToString) = 0 Then
                e.Value = "NIL"
                e.FormattingApplied = True
            End If
        End If
    Catch ex As Exception

    End Try


End Sub

But now I'm stumped on the WPF equivalent

1

1 Answers

0
votes

I am not sure if there is an easy way to do this, i'd do it like this which does seem to work:

Define a custom column with a custom converter:

<DataGrid.Resources>
    <local:ZeroToNilConverter x:Key="ZeroToNilConverter"/>
</DataGrid.Resources>
<DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Id, Converter={StaticResource ZeroToNilConverter}}" Header="Test"/>
</DataGrid.Columns>
//Sorry, i do not speak VB...
public class ZeroToNilConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input = 0;
        try
        {
            input = (int)value;
        }
        catch (Exception)
        {
            return value;
        }

        if (input == 0) return "NIL";
        else return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = value as string;
        if (input != null)
        {
            if (input == "NIL") return 0;
            else return value;
        }
        else
        {
            return value;
        }
    }
}