-5

In my program I am using a database containing a Time (string previousTimeVASN). I have a timer to clock total seconds. i would like to display the sum of previousTimeVASN + the total seconds.

I have error showing:

"System.FormatException: 'Input string was not in a correct format.'" at line: double test1 = Convert.ToDouble(previousTimeVASN);

any suggestion are much appreicated.

private void sNbtn_Click(object sender, RoutedEventArgs e)
{
     TabControl.SelectedIndex = 1;
     dtVASN.Tick += new EventHandler(dtVASN_Tick);
     dtVASN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}

void dtVASN_Tick(object sender, EventArgs e)
{
     if (swVASN.IsRunning)
     {
         TimeSpan tsVASN = swVASN.Elapsed;
         double test = tsVASN.TotalSeconds;
         double test1 = Convert.ToDouble(previousTimeVASN);
         txtVASN.Text = (test + test1).ToString(); 
     }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88

1 Answers1

1

The method Convert.ToDouble will throw FormatException if value is not a number in a valid format. You are getting the same here means either the value in previousTimeVASN is not a number or it is not in the expected format. Here is an alternate option for you to check whether the conversion is possible or not, that is, Double.TryParse Method

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

So the code can be revamped as like the following:

if (swVASN.IsRunning)
{
     TimeSpan tsVASN = swVASN.Elapsed;
     double test = tsVASN.TotalSeconds;
     double test1;
     Double.TryParse(previousTimeVASN, out test1);
     txtVASN.Text = (test + test1).ToString(); 
}

if you want to alert the user that the second number is not valid then you can use the return value of parse like the following:

if(Double.TryParse(previousTimeVASN, out test1))
   txtVASN.Text = (test + test1).ToString(); 
else
   txtVASN.Text = "previous Time VASN is not valid:'
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Thank you very much everyone. I didnt notice i already saved non-number text into previousTimeVASN. after i corrected it, it works perfect. again. thank you! – user9939859 Jul 13 '18 at 07:22