2015-10-16 19 views
0

我在這一行int number = int.Parse(Days);型鑄造收到錯誤 - 輸入字符串的不正確的格式

輸入字符串的不正確的格式得到一個錯誤。

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; 
} 

存儲過程:

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

select ApprovedDays from tbl_Category where [email protected] 

end 
GO 
+0

什麼是'Days'到底是什麼?你調試了你的代碼並檢查它嗎? –

+0

條件運算符執行兩次查詢。將其存儲在一個變量中。 –

+0

顯示完整的代碼。 –

回答

1
  • 如果該行不存在的cmdLog.ExecuteScalar()結果是null,沒有問題。
  • 如果該行存在但在此列中有NULLcmdLog.ExecuteScalar()的結果爲DBNull.Value,DBNull.Value.ToString()返回一個空字符串,該字符串會導致您的異常。

相反,你應該將它轉換爲corect類型,這似乎是一個int

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

除此之外,有條件的經營者執行兩次查詢。將其存儲在一個變量中。

+0

我可以使用Convert.ToInt32嗎? –

+0

@krishnamohan:是的,你可以,但不是在數據庫中的'int'呢? –

1

從你的問題,它看起來像你試圖解析一個空字符串。
可嘗試

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

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

MSDN說:int.TryParse一些它的32位有符號整數等價的字符串表示形式。返回值指示轉換是否成功