Dashzapp
Dashzapp

Reputation: 143

Long.Tryparse Overload & Convert error C#

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.

Upvotes: 1

Views: 10253

Answers (2)

Jebastin
Jebastin

Reputation: 1

Convert the object (dts.Tables[0].Rows[0]["RECID"]) into string. That's it.

dts.Tables[0].Rows[0]["RECID"].ToString()

Upvotes: 0

Neil Fenwick
Neil Fenwick

Reputation: 6184

Two options:

If your data is a string, then cast it as a string

long Recid = 0;
Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid)

otherwise, call .ToString() on it

long Recid = 0;
Boolean checkrecid = long.TryParse(dts.Tables[0].Rows[0]["RECID"].ToString(), out Recid)

The reason you need to do this is because the long.TryParse() method only accepts an instance of a string as its first parameter http://msdn.microsoft.com/en-us/library/zc2x2b1h.aspx

The data coming out of your dataset is typed as an object and therefore the Int64.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 object in 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.

Upvotes: 8

Related Questions