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

Asked

Viewed 2,761 times

1

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

Currently:

Atualmente:

How I’d like you to stay:

inserir a descrição da imagem aqui

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

  • Do you use predefined datagriview columns or let it generate the columns automatically?... if it is default... and only edit the column... it has a SUB-property in it called Nullvalue... try to put null or 01/01/0001

  • Have you ever tried to put this column in your BD as not mandatory and use the type DateTime? instead of DateTime? The difference is that the first accepts null values unlike the second.

2 answers

3

Answer given before OP indicates you are using Windowsforms.

Solution for WPF.

Use a Valueconverter to convert Datetime in string.
When making the conversion if the value of the Datetime is DateTime.MinValue return string.Empty; otherwise return 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 shall first declare it in the section <Windos.Resources> of his Window.

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

Then assign it to the attribute Convert of Binding of Datagridtextcolumn

<DataGrid.Columns>
    <DataGridTextColumn Header="Data" Binding="{Binding data, Converter={StaticResource DateTimeToString}" />
</DataGrid.Columns>

1

EDIT:

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

You can do something like:

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

or

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

that should work

  • You can check tbm if the data.Year == 0001 and if the cell value is not defined.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.