Reputation: 288
I want the DispatcherTimer to read time values from the textbox : objTextBox. I tried this code however it seems that TimeSpan is not compatible with strings or did I do anything wrong?
Error: Argument 1: cannot convert from 'string' to 'long'
Also; Does the Time have to look like this in textbox: 0, 0, 1 or 00:00:01?
Code here:
private void testing()
{
string theText = objTextBox.Text;
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(listjob3_Tick);
dispatcherTimer.Interval = new TimeSpan(theText);
dispatcherTimer.Start();
}
Upvotes: 1
Views: 151
Reputation: 13887
I'm guessing your exception is here:
dispatcherTimer.Interval = new TimeSpan(theText);
Use this instead:
dispatcherTimer.Interval = new TimeSpan(Convert.ToInt64(theText));
Upvotes: 1
Reputation: 67948
To convert to a TimeSpan
from a string
you could leverage TimeSpan.Parse
, but you'd have to conform to this format [ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
where:
ws is Optional white space.
- is An optional minus sign, which indicates a negative TimeSpan.
d is Days, ranging from 0 to 10675199.
. is A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.
hh is Hours, ranging from 0 to 23.
: is The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.
mm is Minutes, ranging from 0 to 59.
ss is Optional seconds, ranging from 0 to 59.
. is A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.
ff is Optional fractional seconds, consisting of one to seven decimal digits.
so just converting days you could in fact use TimeSpan.Parse
and just pass in the string - but if you wanted to convert minutes it would take some massaging of the input like this:
var input = string.Format("00:{0}", objTextBox.Text.PadLeft(2, '0'));
and so then you could issue var timeSpan = TimeSpan.Parse(input);
because you've formatted it properly and the Parse
will succeed. Another option is to turn minutes into days I guess, but that would require some floating point work and is really, IMO, not as good of an option.
Upvotes: 1
Reputation: 74385
@Sneakybastardd: have you read the TimeSpan
documentation regarding constructor overloads? You'll note that none of them take string arguments: integer types are required.
After reading the documentation, you might find these TimeSpan
methods useful:
Parse()
ParseExact()
TryParse()
With respect to format, See "Standard TimeSpan Format Strings" and "Custom TimeSpan Format Strings". Also do a little research on the various default TimeSpan formats for different cultures if that comes into play at all.
Upvotes: 0