C# – “FormatException was unhandled” Input string was not in a correct format

asp.netcnet

Here I am trying to write a function that returns me value based on the following condition…

IF

Variable is NULL return me DBNull.Value

ELSE

Convert Variable into DataType whose DataTypeCode has been provided to me as a parameter of function. eg.

Now while converting a variable into required DataType, an exception is thrown "FormatException was unhandled". Input string was not in a correct format.

How do I resolve this error please help.

Here is my code…

    public object ReturnDBNullOrRequiredDatatype(object IsThisObjectANull, TypeCode DataTypeCode)

    {
return IsThisObjectANull == null ? DBNull.Value : Convert.ChangeType(IsThisObjectANull, DataTypeCode);

    }

i am calling this function as
ReturnDBNullOrRequiredDatatype(txtFirstName.text, TypeCode of an Integer variable)
2nd parameter is a data type into which first parameter is to be converted.

I am trying to return this value to

SqlParameter spAmount = new SqlParameter(…)
spName.value=DbNull.value

or

SqlParameter spName = new SqlParameter(…)
spAmount.value=Cint(txtName.text)

I am trying to do this with that function.
I am making sure that the value being passed to that function will fulfill my conversion type but this error is still occuring.

Best Answer

The documentation for Convert.IsDBNull says the following:

Returns an indication whether the specified object is of type DBNull.

The documentation also specifically states that DBNull.Value is not equivalent to a null reference or string.Empty.

So the method should return false if you pass null or an empty string to it. I believe that what you really want to do is this:

if (IsThisObjectANull == null)
    return DBNull.Value;
else
    return Convert.ChangeType(IsThisObjectANull, DataTypeCode);

...or the shorter version:

return IsThisObjectANull == null ? DBNull.Value : Convert.ChangeType(IsThisObjectANull, DataTypeCode);