locked
Update label using 2 textboxes to calculate time RRS feed

  • Question

  • User-1901014284 posted

    Hi,

    I have 2 textboxes which I have used to populate a time by using code along the lines of endtimeTextbox.Text - starttimeTextbox.Text = TimedurationLabel.Text

    This work with no issue and all data is saved into my DataBase. The issue i am having is when i retrieve the data from the DataBase and populate the 2 Textboxes and Label I am unable to get the label to re-calculate the time duration based on the changes made in the 2 textboxes.

    Please see below my code :

    .ASPX


    <asp:TextBox ID="StartTime" runat="server" Height="30px" Width="200px" Font-Names="Arial" Font-Size="Medium" />
    <br />
    <asp:TextBox ID="EndTime" runat="server" Height="30px" Width="200px" Font-Names="Arial" Font-Size="Medium" AutoPostBack="true" OnTextChanged="TravelTimeEndStartTextBox_TextChanged" />
    <br />

    <asp:Label runat="server" ID="TotalDurationLabel;" CssClass="auto-style5" Font-Bold="True" Font-Names="Arial" Font-Size="Large" Height="30px" Width="100px" Visible="False">0</asp:Label>

    C# Code:

    //below code is used to get/set (From a class) the data from the DataBase and display in the relevant Textboxes and Label. Also would there be a way to display the time in the format of "HH:MM" rather than "HH:MM:ss"?) 

    if (!IsPostBack)
    {
    var expenses = repo.Find(Int32.Parse(Request.QueryString["id"]));

    StartTime.Text = expenses.TravelStartTimeStart.ToString();
    EndTime.Text = expenses.TravelEndTimeStart.ToString();
    TotalDurationLabel.Text = expenses.TravelStart_DurationMinutes;

    }

    //I have the below code on Text_Changed which should be triggering the update of the label but the event does not trigger

    protected void EndTime_TextChanged(object sender, EventArgs e)
    {
    DateTime StartTime;
    DateTime EndTime;
    if (DateTime.TryParseExact(EndTime.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out Etime) &&
    DateTime.TryParseExact(StartTime.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out Stime))
    {
    TotalDurationLabel.Text = (Stime- Etime).TotalMinutes.ToString("00.##");
    }
    int totalMinutesTravelStart = Convert.ToInt32(TotalDurationLabel.Text);
    TimeSpan tsts = TimeSpan.FromMinutes(totalMinutesTravelStart);

    //this converts the minutes to hours label 
    TravelTimeStartDurationHoursLabel.Text = string.Format("{0} : {1}", tsts.Hours, tsts.Minutes);
    }

    I am wondering if there is a better way to achieve the above or if I have made a mistake in my code?

    Any help would be greatly appreciated.

    Many thanks

    Jonny

    Friday, September 21, 2018 12:12 PM

Answers

  • User475983607 posted

    So the problem is the code block is not running, you're breakpoint is not getting hit, not the calculation?

    Also the code is confusing... Here you've declared STime and ETime...

    TimeSpan STime= TimeSpan.Parse(StartTimeTextBox.Text);
    TimeSpan ETime = TimeSpan.Parse(EndTimeTextbox.Text);

    and a second time...

    if (TimeSpan.TryParseExact(EndTimeTextbox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out ETime ) &&
    TimeSpan.TryParseExact(StartTimeTextBox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out STime))

    but the calculation is using completely different variables.

    {
      TravelTimeStartDurationMinutesLabel.Text = (TravelStartdatetimeEnd - TravelStartdatetimeStart).TotalMinutes.ToString("00.##");
    }

    I built a basic console app to test the TimeSpan calculation.  I suggest you do the same as well as read the support docs.  But at this point it seems you have general issue with the code that must be worked out of the code is not running.

            static void Main(string[] args)
            {
                TimeSpan interval = new TimeSpan(0, 2, 10, 34, 0);
                TimeSpan interval2 = new TimeSpan(0, 3, 9, 0, 0);
                TimeSpan result = interval2 - interval;
    
                Console.WriteLine(result.TotalMinutes.ToString("00.##"));
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 24, 2018 3:55 PM

All replies

  • User-1716253493 posted

    Intead of calculating hours and minutes, you can directly format tsts

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings

    AFAIK, you don't need to save tsts to db because saving starttime and endtime is enough

    Friday, September 21, 2018 1:00 PM
  • User-893317190 posted

    Hi jonnygareth30,

    If you want the time in a correct format, you could use a time plugin to limit the format the user could enter.

    https://plugins.jquery.com/tag/time/

    Or bootstrap datatimepicker  https://github.com/Eonasdan/bootstrap-datetimepicker

    And I haven't find your output variable for the method DateTime.TryParseExact.

    Below is my code.

      protected void TextBox2_TextChanged(object sender, EventArgs e)
            {
                DateTime Stime;
                DateTime Etime;
                if (DateTime.TryParseExact(EndTime.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out Etime) &&
                DateTime.TryParseExact(StartTime.Text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out Stime))
                {
                    TotalDurationLabel.Text = (Etime-Stime).TotalMinutes.ToString("00.##");
                }
                int totalMinutesTravelStart = Convert.ToInt32(TotalDurationLabel.Text);
                TimeSpan tsts = TimeSpan.FromMinutes(totalMinutesTravelStart);
                           
                TravelTimeStartDurationHoursLabel.Text = string.Format("{0} : {1}", tsts.Hours, tsts.Minutes);
            }

    About the TextChanged event , you should change the text of the textbox and  make the textbox  out of focus or the event will not  be fired,

    Best regards,

    Ackerly Xu

    Monday, September 24, 2018 9:44 AM
  • User-1901014284 posted

    Thank you for the response, I have noticed where I went wrong following your previous post in regards to output of the variables you have highlighted with the below code:

    TimeSpan STime= TimeSpan.Parse(StartTimeTextBox.Text);
    TimeSpan ETime = TimeSpan.Parse(EndTimeTextbox.Text);


    if (TimeSpan.TryParseExact(EndTimeTextbox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out ETime ) &&
    TimeSpan.TryParseExact(StartTimeTextBox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out STime))
    {
    TravelTimeStartDurationMinutesLabel.Text = (ETime- StartTimeTextBox).TotalMinutes.ToString("00.##");
    }

    int totalMinutesTravelStart = Convert.ToInt32(TravelTimeStartDurationMinutesLabel.Text);

    //this code is used to convert minutes to hours and minutes
    TimeSpan tsts = TimeSpan.FromMinutes(totalMinutesTravelStart);
    TravelTimeStartDurationHoursLabel.Text = string.Format("{0} : {1}", tsts.Hours, tsts.Minutes);

    I am now struggling as to how I can calculate the 2 textboxes (StartTimeTextBox and EndTimeTextBox) together on the page load. the values are populated for the STime and ETime but the below code does not run:

    TravelTimeStartDurationMinutesLabel.Text = (ETime- StartTimeTextBox).TotalMinutes.ToString("00.##");

    Any help on how I can get the above to calculate on the page load would be greatly appreciated.

    Thanks

    Jonny

    Monday, September 24, 2018 2:23 PM
  • User475983607 posted

    I recommend reading the TimeSpan API documents first.

    https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=netframework-4.7.2

    Use the TimeSpan structure to build time calculations.  

    I am now struggling as to how I can calculate the 2 textboxes (StartTimeTextBox and EndTimeTextBox) together on the page load. the values are populated for the STime and ETime but the below code does not run:

    TravelTimeStartDurationMinutesLabel.Text = (ETime- StartTimeTextBox).TotalMinutes.ToString("00.##");

    You are confusing a string with a TimeSpan type.  First convert the StartTimeTextBox.Text value to a TimeSpan type then apply math.

    Monday, September 24, 2018 2:40 PM
  • User-1901014284 posted

    My apologies, StartTimeTextBox is supposed to be STime. 

    Monday, September 24, 2018 2:52 PM
  • User475983607 posted

    My apologies, StartTimeTextBox is supposed to be STime. 

    I do not understand the problem you are trying to solve.  Is the problem the code is not running, throwing an error, not formatted as expected?

    Monday, September 24, 2018 2:55 PM
  • User-1901014284 posted

    Sorry if i am not very clear on the issue:

    The below code pulls the Start Time and the End time (HH:MM:SS) from my database and this is done with no issues.

    TimeSpan STime= TimeSpan.Parse(StartTimeTextBox.Text);
    TimeSpan ETime = TimeSpan.Parse(EndTimeTextbox.Text);


    if (TimeSpan.TryParseExact(EndTimeTextbox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out ETime ) &&
    TimeSpan.TryParseExact(StartTimeTextBox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out STime))

    The below line I am trying to use to calculate the StartTime and the EndTime (the above textboxes) and display in a label the duration in minutes by subtracting the EndTime from the StartTime.  

    {
    TravelTimeStartDurationMinutesLabel.Text = (TravelStartdatetimeEnd - TravelStartdatetimeStart).TotalMinutes.ToString("00.##");
    }

    The above runs on the page load event within a postback function but the subtraction does not seem to be running at all when I am debugging my code.

    Again my apologies if I am not clear in my explanation.

    Many thanks

    Jonny

    Monday, September 24, 2018 3:14 PM
  • User475983607 posted

    So the problem is the code block is not running, you're breakpoint is not getting hit, not the calculation?

    Also the code is confusing... Here you've declared STime and ETime...

    TimeSpan STime= TimeSpan.Parse(StartTimeTextBox.Text);
    TimeSpan ETime = TimeSpan.Parse(EndTimeTextbox.Text);

    and a second time...

    if (TimeSpan.TryParseExact(EndTimeTextbox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out ETime ) &&
    TimeSpan.TryParseExact(StartTimeTextBox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out STime))

    but the calculation is using completely different variables.

    {
      TravelTimeStartDurationMinutesLabel.Text = (TravelStartdatetimeEnd - TravelStartdatetimeStart).TotalMinutes.ToString("00.##");
    }

    I built a basic console app to test the TimeSpan calculation.  I suggest you do the same as well as read the support docs.  But at this point it seems you have general issue with the code that must be worked out of the code is not running.

            static void Main(string[] args)
            {
                TimeSpan interval = new TimeSpan(0, 2, 10, 34, 0);
                TimeSpan interval2 = new TimeSpan(0, 3, 9, 0, 0);
                TimeSpan result = interval2 - interval;
    
                Console.WriteLine(result.TotalMinutes.ToString("00.##"));
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 24, 2018 3:55 PM
  • User-1901014284 posted

    Thank you mgebhard, after your explanation I have found the error I had made. by removing the below lines I was able to get the code to run successfully.

    Again thank you for your help.

    if (TimeSpan.TryParseExact(EndTimeTextbox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out ETime ) &&
    TimeSpan.TryParseExact(StartTimeTextBox.Text, "HH:mm", CultureInfo.InvariantCulture, TimeSpanStyles.None, out STime))

    Kind regards

    Jonny

    Thursday, September 27, 2018 9:18 AM