I have a method which is connecting to a database via Odbc. The stored procedure which I'm calling has a return value which from the database side is a 'Char'. Right now I'm grabbing that return value as a string and using it in a simple if statement. I really don't like the idea of comparing a string like this when only two values can come back from the database, 0 and 1.
OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn);
fetchCommand.CommandType = CommandType.StoredProcedure;
fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter);
fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1)
.Direction = ParameterDirection.Output;
fetchCommand.ExecuteNonQuery();
string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString();
if (returnValue == "1")
{
return true;
}
What would be the proper way to handle this situation. I've tried 'Convert.ToBoolean()' which seemed like the obvious answer but I ran into the 'String was not recognized as a valid Boolean. ' exception being thrown. Am I missing something here, or is there another way to make '1' and '0' act like true and false?
Thanks!
This question is related to
c#
.net
asp.net
odbc
boolean-logic
Set return type to numeric - you don't need a char (so don't use it); a numeric value (0/1) can be converted with Convert.ToBoolean(num)
Otherwise: use Kevin's answer
In a single line of code:
bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))
Or if the Boolean value is not been returned, you can do something like this:
bool boolValue = (returnValue == "1");
You can use that form:
return returnValue.Equals("1") ? true : false;
Or more simply (thanks to Jurijs Kastanovs):
return returnValue.Equals("1");
My solution (vb.net):
Private Function ConvertToBoolean(p1 As Object) As Boolean
If p1 Is Nothing Then Return False
If IsDBNull(p1) Then Return False
If p1.ToString = "1" Then Return True
If p1.ToString.ToLower = "true" Then Return True
Return False
End Function
(returnValue != "1" ? false : true);
If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1"
as true
and anything else as false
(as Kevin does). If you wanted the conversion to fail if anything other than "1"
or "0"
is returned, then the following would suffice (you could put it in a helper method):
if (returnValue == "1")
{
return true;
}
else if (returnValue == "0")
{
return false;
}
else
{
throw new FormatException("The string is not a recognized as a valid boolean value.");
}
If you don't want to convert.Just use;
bool _status = status == "1" ? true : false;
Perhaps you will return the values as you want.
Source: Stackoverflow.com