I am working on a program in WPF for the first time. I have a ListView in GridView mode displaying data from a bound dataset (which is grabbed from a database).
In my database, "date of birth" is not a required field. As such, any record without a dob had the value set to DateTime.MinValue
. On each of these minimum value dates, the date shows in the cell as 01/01/0001. I am trying to find a way to either format the cell so that DateTime.MinValue
doesn't show, or replace each MinValue
with ""
.
My thought was to either use the "Loaded" event of the textblock the date is in and replace each instance of "01/01/0001", or loop through the dataset before sending it to the GridView and remove/replace them there. I've not had any luck figuring out how to do either.
My xaml code for the GridView is:
<Grid>
<ListView x:Name="resultsListView" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" Margin="0,54,0,28" ItemsSource="{Binding Path=Table}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=LastName}"
Header="Last Name"
Width="150"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=FirstName}"
Header="First Name"
Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=MiddleName}"
Header="Middle Name"
Width="100"/>
<GridViewColumn Header="Date of Birth" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock TextAlignment="Justify" Text="{Binding Path=DateOfBirth, StringFormat='{}{0:MM/dd/yyyy}'}" Loaded="TextBlock_Loaded" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
Code for the DataSet:
private void FillListView(DataSet ds)
{
if (resultsListView.Items.Count != 0)
{
resultsListView.Items.Clear();
}
resultsListView.DataContext = ds.Tables[0].DefaultView;
}
Any advice on how to show blanks for DateTime.MinValue
in my GridView would be much appreciated!
I would make an IValueConverter
that deals with this, and include it in your binding expression.
In your resources:
<local:DateTimeConverter x:Key="DateTimeConverter" />
Then update your binding:
<TextBlock Text="{Binding Path=DateOfBirth,
Converter={StaticResource DateTimeConverter},
ConverterParameter='MM/dd/yyyy'}" />
Then define the class:
public class DateTimeConverter : IValueConverter
This has two methods. You need only to implement Convert
(unless you're planning on using two-way binding). In this method, you can take the format string via a paramater (as I've passed in the binding expression above) and also check for DateTime.MinValue
and return a blank string.