Reputation: 267
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
Upvotes: 0
Views: 192
Reputation: 460018
cmdLog.ExecuteScalar()
is null
, no problem.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.
Upvotes: 1
Reputation: 1881
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
Upvotes: 1