Search code examples
c#sql-serverwpfdatetimetextbox

WPF: How do I get only Time from textbox?


I have a datatable with a column Total time active:Total which I want to filter on a minimal and maximal time e.g. show only active times between 00:02:00 and 00:30:00. My Stored Procedure works with these START and END times to filter.

In my WPF app i have a textbox and want to use this to filter said table.

(note, these aren't times of a day just times in general, i could be over 24 hours.)

What I found was that I need to convert the textbox string to DateTime, but I'm not sure how to do this since I'm very new to databases and WPF. In xaml I tried using:

<TextBox x:Name="Activefrom"
    Text="{Binding Path=TotalStart,  StringFormat=' HH:mm:ss '}"/>

And in the code-behind converting the string with:

DateTime dateTimeStart = DateTime.ParseExact(Activefrom.Text, "HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

but i get the error:

System.FormatException: 'String was not recognized as a valid DateTime.'

Since it's times over 24 hours I'm not sure if I should use DATETIME but I tried it anyway since in this case the table doesn't go over 24 hours.

How can I bind the textbox as Time so I can use my SP to filter a datatable on times only


Solution

  • Sounds like you should have a look at the TimeSpan struct instead of DateTime. Also, I would probably split the input into one textbox for number of hours and one for number of minutes (depending on the range of duration times in your data).