John
John

Reputation: 3945

string was not recognized as valid BOOL

 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

Answers (5)

Kavindu Dodanduwa
Kavindu Dodanduwa

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, contains true if value is equal to TrueString or false if value is equal to FalseString. If the conversion failed, contains false.

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

Wai Ha Lee
Wai Ha Lee

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

HelloWorld
HelloWorld

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

SWol
SWol

Reputation: 48

ExecuteScalar not returning boolean. Read documentation Here

Upvotes: 0

Marc Gravell
Marc Gravell

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

Related Questions