Reputation: 3945
oComm = CreateCommand("IsMapAccessExist", spParams, TypeOfConnectionString.GeoAppBuilder);
bool exists = true;
exists = Boolean.Parse(oComm.ExecuteScalar().ToString());
return exist
exists has the value 'true' but it throws the error
FormatException was caught
String was not recognized as a valid Boolean.
Upvotes: 0
Views: 2229
Reputation: 13059
Though it's late , here is an answer using Boolean.TryParse
.
bool exists; // No need to assign
Boolean.TryParse(oComm.ExecuteScalar().ToString(),exists); // using TryParse
return exist;
Explanation : (MSDN)
If the conversion
succeeded
, containstrue
if value is equal toTrueString
orfalse
if value is equal toFalseString
. If the conversionfailed
, containsfalse
.
You will always get a desired value even if the value is not a valid TrueString
or FalseString
field.
Intention is to avoid exceptions at any cost. Even failure will return a false
but program will continue without a stop.
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.
Upvotes: 0
Reputation: 8805
Boolean.Parse
MUST be passed either "True" (Boolean.TrueString
) or "False" (Boolean.FalseString
).
You might be better off using Boolean.TryParse
instead, e.g.:
string value = "true";
bool couldParseString = Boolean.TryParse(value, out value);
if ( couldParseString )
{
// do some stuff
}
else
{
// handle the string not being correct
}
Note: you should generally aim to use {type}.TryParse instead of Parse.
Upvotes: 0
Reputation: 1103
.ExecuteScalar()
returns the first column of the first row. To make it work, do something like this:
int col = (int)oComm.ExecuteScalar();
if(col == null)
exists = false;
else
exists = true;
Upvotes: 1
Reputation: 1062492
It sounds to me like ExecuteScalar
returned something that wasn't "True"
or "False"
; perhaps "1"
or "0"
. Here's how you debug it:
var tmp = oComm.ExecuteScalar().ToString();
exists = Boolean.Parse(tmp);
Then look at what tmp
holds in a debugger.
Upvotes: 3