Search code examples
c#wpfdatetimetextbox

textbox.SelectionStart continuously in this event call


so i have a textbox (named time) in my WPF app that I want a user inputted time. I also have buttons that add/subtract an hour/minute based on where the cursor is located. so if the cursor is on the first two elements it is updating the hour 10:30 to 11:30 on the minutes 10:30 to 10:31

 private void up_Click(object sender, RoutedEventArgs e)
    {
        if (time.SelectionStart == 0 || time.SelectionStart == 1 || time.SelectionStart == 2)
        {
            date1 = date1.AddHours(1);
        }

        if (time.SelectionStart == 3 || time.SelectionStart == 4 || time.SelectionStart == 5)
        {

            date1 = date1.AddMinutes(1);
        }

        if (time.SelectionStart == 7 || time.SelectionStart == 6 || time.SelectionStart == 8)
        {
            date1 = date1.AddHours(12);
        }

        time.Text = date1.ToString("hh:mm tt");
    }`

the problem is if I routinely press this button it will default back to the hour position instead of keep updating the minute if the cursor is in the minute position How would I go about making it not default back and accept the cursor position?

if you press up and the cursor is in the minutes position it will go correctly 10:30 to 10:31 once but the second click will update the hour to 11:31 instead of 10:32.


Solution

  • as Elhamer suggested. storing the selection properties in a variable and then restoring them after the text set.

            int position = time.SelectionStart;
            int backup = position;
    
            if (position == 0 || position == 1 || position== 2)
            {
                date1 = date1.AddHours(-1);
            }
    
            if (position == 3 || position == 4 || position == 5)
            {
    
                date1 = date1.AddMinutes(-1);
            }
    
            if (position == 7 || position == 6 || position == 8)
            {
                date1 = date1.AddHours(-12);
            }
    
    
            time.Text = date1.ToString("hh:mm tt");
    
            time.SelectionStart = backup;