简体   繁体   中英

getting error in type casting - Input string was not in a correct format

I'm getting an error in this line int number = int.Parse(Days);

Input string was not in a correct format.

public string GetApprovedLimit(int CategoryId)
{
    SqlConnection connection = new SqlConnection(GetConnectionString());
    SqlCommand cmdLog = new SqlCommand();
    cmdLog.CommandType = CommandType.StoredProcedure;
    cmdLog.Connection = connection;
    cmdLog.Transaction = Trans;
    connection.Open();
    cmdLog.CommandText = "ApprovedDays";
    cmdLog.Parameters.AddWithValue("@CategoryId", CategoryId);
    string Days = cmdLog.ExecuteScalar() == null ? "1" : cmdLog.ExecuteScalar().ToString();
    connection.Close();
    int number = int.Parse(Days);
    Days = (number + 20).ToString(); // Added extra 20 days for late link submission
    return Days;
}

stored procedure:

Create Proc [dbo].[ApprovedDays]
(
    @CategoryId int
)
as begin

select ApprovedDays from tbl_Category where CategoryId=@CategoryId

end
GO
  • If the row does not exist the result of cmdLog.ExecuteScalar() is null , no problem.
  • If the row exists but has NULL in this column, the result of cmdLog.ExecuteScalar() is DBNull.Value , DBNull.Value.ToString() returns an empty string which causes your exception.

Instead you should cast it to the corect type which seems to be an int :

int days = 1;
object obj = cmdLog.ExecuteScalar();
if(obj != null && DBNull.Value != obj)
{
    days = (int) obj;
}

Apart from that, the conditional operator executes the query twice. Store it in a variable.

From your question it looks like you are trying to parse an empty string.
Things you can try

int number = string.IsNullOrEmpty(days) ? 0 : int.Parse(days);

or

     if (int.TryParse(days, out number))
        {// Conversion succeeded}
     else
       {
         //failed
        }

MSDN says: int.TryParse Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM