Do not display null value (01/01/0001) of a Datetime in a DataGridView

1

My DataGridView has some fields DateTime with value null (01/01/0001). How do I not display these values, leaving the field blank?

Currently:

HowIwouldlikeyoutostay:

I'm using WindowsForm , C # and .Net Framework 3.5 . Remembering that I use databinding in my DataGridView .

    
asked by anonymous 29.10.2014 / 11:04

2 answers

3

Answer given before the OP indicates that you are using WindowsForms .

Solution for WPF.

Use a ValueConverter to convert DateTime into string . When doing the conversion if the value of DateTime is DateTime.MinValue it returns string.Empty; otherwise it returns dateTime.ToString()

[ValueConversion(typeof(DateTime), typeof(string))]
public class DateTimeToString : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
        {
            var dateTime = (DateTime)value;
            if (dateTime == DateTime.MinValue)
            {
                return string.Empty;
            }
            return dateTime.ToString();
        }
        throw new ArgumentException("value");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var dateString = (string) value;
            if (string.IsNullOrEmpty(dateString))
            {
                return DateTime.MinValue;
            }
            return DateTime.Parse(dateString);
        }
        throw new ArgumentException("value");
    }
}

To use the ValueConverter you must first declare it in the <Windos.Resources> section of your Window .

<Window.Resources>
    <local:DateTimeToString x:Key="DateTimeToString" />
</Window.Resources>

Then assign it to the Binding attribute of the DataGridTextColumn

<DataGrid.Columns>
    <DataGridTextColumn Header="Data" Binding="{Binding data, Converter={StaticResource DateTimeToString}" />
</DataGrid.Columns>
    
29.10.2014 / 11:55
1

EDIT:

It was bad, I had not seen it using the databinding, in this case I think my solution does not apply, but it is valid for other cases.

You can do something like this:

if (data != DateTime.MinValue)
   tabela[indexColuna, indexLinha].Value = data;

or

if (data.Year  != 0001)
   tabela[indexColuna, indexLinha].Value = data;

this should work

    
29.10.2014 / 12:03