I am having difficulties with this code where I’m trying to put a certain conversion for a long from data out of a dataset.
I’m trying to check if it’s possible to convert the value inside that position in the dataset. If it doesn’t work, it means that there are no items in the dataset, because all the other entrants (readed from a txtfile) are valid
Code:
long Recid = 0;
Boolean checkrecid = long.TryParse(dts.Tables[0].Rows[0]["RECID"], out Recid)
Errors:
The best overloaded method match for 'long.TryParse(string, out long)' has some invalid arguments and
Argument 1: cannot convert from 'object' to 'string'
Thanks in advance.
Two options:
If your data is a string, then cast it as a string
otherwise, call
.ToString()on itThe reason you need to do this is because the
long.TryParse()method only accepts an instance of astringas its first parameter http://msdn.microsoft.com/en-us/library/zc2x2b1h.aspxThe data coming out of your dataset is typed as an
objectand therefore theInt64.TryParse()method can’t be sure if it is a string and it is failing. (In general, programming does not allow for ambiguity and that is why the TryParse method doesn’t attempt to convert it for you – you must be explicit about what it is you want and what you provide).Datasets are very flexible because you can store any
objectin them, but its more work for the programmer to cast the type back after getting it back out again. Other alternatives, like strongly-typed datasets, get around that problem by being more rigid about what types you can store in them, but then you don’t have to keep casting things all the time.