Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello.
I have an app like this (https://i.stack.imgur.com/cVUq1.jpg[^]). I want the user to be able to add interview date with a DatePicker (DatePick) to enter it for a selected item in the Interview Date column, and then manually enter a time e.g. '11:115' into the Interview Time column by first selecting the item (each row) and then clicking the relevant buttons.

[![enter image description here][1]][1]

Right now it enters the date correctly displaying the date part only in the Interview Date column. however, when I enter the time, it changes Interview date for today's date (20/12/2022).

My code for a .xaml.cs:

C#
    public partial class Shortlist : Window
    {
     
//      list of shortlisted clients
        List<ShortlistedClient> shlclients = new List<ShortlistedClient>();

        public DateTime? SelectedDateFormat { get; private set; }

        // generate dummy data for a shortlist
        public Shortlist()
        {
            InitializeComponent();     
            DataContext = shlclients;
            shlclients.Add(new ShortlistedClient("Rich", "07515118265", "rich@gmail.com", "Glasgow", "Office", "BSc", "more than 3 years", "Yes", "No"));
            shlclients.Add(new ShortlistedClient("Steve", "07515118265", "steve@gmail.com", "Glasgow", "Construction", "High School", "1-3 years", "Yes", "No"));
            shlclients.Add(new ShortlistedClient("Simon", "07485999005", "simon@gmail.com", "Edinburgh", "Office", "MSc", "more than 3 years", "Yes", "No"));
        }


        // method to add date to each selected client
        private void addInterviewDate(object sender, RoutedEventArgs e)
        {
            ShortlistedClient sc = dgr.SelectedItem as ShortlistedClient;

            if (sc != null)
            {
                sc.DT = DatePick.SelectedDate;
            }

        }
        // method to add time to each selected client
        private void addInterviewTime(object sender, RoutedEventArgs e)
        {
            ShortlistedClient sc = dgr.SelectedItem as ShortlistedClient;

             if (sc != null && DateTime.TryParse(textBox.Text, out DateTime result))

            {
                 sc.DT = result;
            }

        }



and my .xaml window code is this:

```
XML
<Window x:Class="WpfApp_Employment_Help.Shortlist"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp_Employment_Help"
        mc:Ignorable="d"
        Title="Shortlist" Height="450" Width="800">
    <StackPanel Margin="0,0,0,73">
        <DataGrid x:Name="dgr" AutoGenerateColumns="False" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" CanUserAddRows="False" Height="154" Width="793">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="Email" Binding="{Binding Email}" />
                <DataGridTextColumn Header="Phone" Binding="{Binding Phone}"/>
                <DataGridTextColumn Header="Location" Binding="{Binding Location}"/>
                <DataGridTextColumn Header="Worktype" Binding="{Binding Worktype}"/>
                <DataGridTextColumn Header="Qualification" Binding="{Binding Qualification}"/>
                <DataGridTextColumn Header="Workexp" Binding="{Binding Workexp}"/>
                <DataGridTextColumn Header="Driving licence" Binding="{Binding Drlicence}"/>
                <DataGridTextColumn Header="Criminal conviction" Binding="{Binding Crconviction}"/>
                <DataGridTextColumn Header="Interested in vacancy" Binding="{Binding InterestedinVac}"/>
                <DataGridTemplateColumn Header="Interview Date">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding DT, StringFormat=dd/MM/yyyy}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <DatePicker SelectedDate="{Binding DT, StringFormat=dd/MM/yyyy}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>

                <DataGridTemplateColumn Header="Interview Time">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding DT, StringFormat=HH:mm}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Add Interview Date" Width="128" FontWeight="Bold" Height="28" Click="addInterviewDate"/>
        <DatePicker x:Name="DatePick" Height="52" Width="200"/>
        <Button Content="Add Interview Time" FontWeight="Bold" Click="addInterviewTime" Height="25" Width="116"/>
        <TextBox x:Name="textBox" TextWrapping="Wrap" Width="197" Height="45" Text="Enter time"/>
        <Button x:Name="BtnRemoveShlClient" Content="Remove Shortlisted Client" FontWeight="Bold" Height="33" Width="220" Click="RemoveShClient"/>
    </StackPanel>
</Window>



Earlier, my ShortlistedClient class and the date time variable was defined like this:

public class ShortlistedClient : Client, INotifyPropertyChanged
    {
        private DateTime? _dt;

        public DateTime? DT
        {
            get { return _dt; }
            set { _dt = value; NotifyPropertyChanged(); }
        }

        public bool InterestedinVac { get; private set; }


        public List<ShortlistedClient> clients { get; set; } = new List<ShortlistedClient>();
        public ShortlistedClient(string n, string p, string e, string l, string wt, string q, string we, string dl, string cc) : base(n, p, e, l, wt, q, we, dl, cc)
        {
            DT = new DateTime();
            InterestedinVac = true;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }




how can I make it work?  I could make date and time as an entry in one column, but I want them to be in two separate columns.
  [1]: https://i.stack.imgur.com/cVUq1.jpg


What I have tried:

I have tried to change my line for the time method like this. It does not give me any errors but now it stops taking the time entries.
it looks like the DatePicker dominates both entries because if I dont pick a particular date with the DatePicker, and click the Add Interview Date button, it clears the values for both Interview Date and Interview Time.
<pre lang="C#">```
        private void addInterviewTime(object sender, RoutedEventArgs e)
        {
            ShortlistedClient sc = dgr.SelectedItem as ShortlistedClient;

            if (sc != null && DateTime.TryParseExact(textBox.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result))
            {
                 sc.DT = result;
            }

        }
Posted
Updated 20-Dec-22 22:36pm
Comments
Graeme_Grant 21-Dec-22 4:44am    
Again, why are you asking the same question more than once? Original question here: How do I get date only out of datepicker in WPF?[^]

1 solution

Quote:
C#
DateTime.TryParseExact(textBox.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result)
If that succeeds, the result will contain a DateTime representing the parsed time on the current day.

You then overwrite the DT property with that value, discarding the date picked in the date picker.

Similarly, when you select a date with the date picker, you overwrite the DT property, discarding the parsed time.

If you're going to enter the date and time separately, you need to store them separately.
C#
public class ShortlistedClient : Client, INotifyPropertyChanged
{
    private DateTime? _date;
    private DateTime? _time;
    
    public DateTime? Date
    {
        get { return _date; }
        set 
        {
            _date = value?.Date;
            OnPropertyChanged();
            OnPropertyChanged(nameof(DT));
        }
    }
    
    public DateTime? Time
    {
        get { return _time; }
        set 
        {
            _time = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(DT));
        }
    }
    
    public DateTime? DT
    {
        get
        {
            if (_time is null) return _date;
            if (_date is null) return _time;
            return _date.Value.Date + _time.Value.TimeOfDay;
        }
    }
    
    ...
C#
private void addInterviewDate(object sender, RoutedEventArgs e)
{
    if (dgr.SelectedItem is ShortlistedClient sc)
    {
        sc.Date = DatePick.SelectedDate;
    }
}

private void addInterviewTime(object sender, RoutedEventArgs e)
{
    if (dgr.SelectedItem is ShortlistedClient sc
        && DateTime.TryParseExact(textBox.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime result))
    {
        sc.Time = result;
    }
}
XAML
<DataGridTemplateColumn Header="Interview Date">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Date, StringFormat=dd/MM/yyyy}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <DatePicker SelectedDate="{Binding Date}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="Interview Time">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Time, StringFormat=HH:mm}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


Edit: If you're using .NET 6 or later, you might want to look at the new DateOnly and TimeOnly types:
Using DateOnly and TimeOnly in .NET 6 - Steve Gordon - Code with Steve[^]
C#
public class ShortlistedClient : Client, INotifyPropertyChanged
{
    private DateOnly? _date;
    private TimeOnly? _time;
    
    public DateOnly? Date
    {
        get { return _date; }
        set 
        {
            _date = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(DT));
        }
    }
    
    public TimeOnly? Time
    {
        get { return _time; }
        set 
        {
            _time = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(DT));
        }
    }
    
    public DateTime? DT
    {
        get
        {
            if (_time is null) return _date?.ToDateTime(default);
            if (_date is null) return DateTime.Today.Add(_time.Value.ToTimeSpan());
            return _date.Value.ToDateTime(_time.Value);
        }
    }
    
    ...
C#
private void addInterviewDate(object sender, RoutedEventArgs e)
{
    if (dgr.SelectedItem is ShortlistedClient sc)
    {
        sc.Date = DateOnly.FromDateTime(DatePick.SelectedDate);
    }
}

private void addInterviewTime(object sender, RoutedEventArgs e)
{
    if (dgr.SelectedItem is ShortlistedClient sc
        && TimeOnly.TryParseExact(textBox.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out TimeOnly result))
    {
        sc.Time = result;
    }
}
 
Share this answer
 
v3
Comments
Graeme_Grant 21-Dec-22 4:45am    
You answered a repeated question. The link is provided above. They asked this yesterday as a second question, then deleted it, only to repost it again today.
Richard Deeming 21-Dec-22 4:47am    
It's related, but I don't think this one counts as a repost. :)
Graeme_Grant 21-Dec-22 4:49am    
Asking for time format rather than date? :thinking:
Richard Deeming 21-Dec-22 4:50am    
No, asking how to enter a date and time separately and have them combined into a single DateTime. :)
Graeme_Grant 21-Dec-22 4:54am    
you could use DateOnly and TimeOnly then combine with new DateTime(...)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900