2012-10-22 3 views
2

저장 프로 시저를 실행하려고하는데 어떤 이유로 계속해서 "Specified cast is not valid"을 말합니다. "hidSelectedExpenseIDs"은 id의 자바 스크립트 배열로 채워진 숨겨진 필드입니다.Convert.ToInt32 (value)를 시도 할 때 지정된 캐스트가 유효하지 않습니다.

예 : "hidSelectedExpenseIDs.Value"은 "123,124,125,126"처럼 보입니다. 따라서 나는 왜 .Split(',')을 가지고있다.

여기 내 코드입니다 :

public void hasExhistingExpenseInvoice() 
{ 
    string[] Expenses = hidSelectedExpenseIDs.Value.Split(','); 

    //check if there is an existing invoice. Then report back to the user so the 
    //user knows if he/she has to check overwrite option. 
    bool invoiceExists = false; 

    foreach (var expense in Expenses) 
    { 
     var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString()); 
     var command = new SqlCommand("p_CaseFiles_Expenses_InvoiceExhists", connection); 
     command.Parameters.Add(new SqlParameter("@ExpenseID", SqlDbType.Int)); 
     command.Parameters["@ExpenseID"].Value = Convert.ToInt32(expense); 
     command.CommandType = CommandType.StoredProcedure; 
     try 
     { 
      connection.Open(); 
      invoiceExists = (bool)command.ExecuteScalar(); 
      if (invoiceExists) 
      { 
       //previous invoice exhists 
       Warning1.Visible = true; 
       Warning1.Text = "There is an exhisting Invoice."; 
      } 
     } 
     catch (SqlException sql) 
     { 
      lblStatus.Text = "Couldn't connect to the Database - Error"; 
      lblStatus.ForeColor = System.Drawing.Color.Red; 
     } 
     catch (Exception ex)//catches exception here 
     { 
      lblStatus.Text = "An error occured"; 
      lblStatus.ForeColor = System.Drawing.Color.Red; 
     } 
     finally 
     { 
      if (connection.State == ConnectionState.Open) 
       connection.Close(); 
     } 
    } 
} 

이 내 저장 프로 시저입니다 :

ALTER PROCEDURE dbo.[InvoiceExhists] 
@ExpenseID int 
AS 
BEGIN 
    SELECT InvNumber FROM dbo.Expenses from ExpID = @ExpenseID 
END 
+0

'hidSelectedExpenseIDs'와 (과) 같은 소리가 항상 포함 된 소리를 포함하지는 않습니다. 이것이 실패 할 때 그 가치는 무엇입니까? – JohnnyHK

+1

중단 점을 사용하여 디버그하고 가변 비용으로 얻는 값을 확인하십시오. – Karthik

+0

'hidSelectedExpenseIDs.Value'에 끝에', '가 없습니까? – manman

답변

4

맞습니다.

쿼리가 숫자를 반환하고이를 Boolean에 직접 캐스팅하려는 경우 C#에서는 수행 할 수 없습니다.

일부 언어는 0이 아닌 값을 true로 해석하며 C#의 경우는 예외이며 예외가 발생합니다.

반환 값을 비교해야합니다.

이 경우 인보이스가 없으면 NULL이 반환되므로 값이 있는지 확인해야합니다.

이 같을 것이다 :

invoiceExists = command.ExecuteScalar() != null ; 

또한 나는이 thread을 읽어 보시기 바랍니다 대신 스칼라 저장 프로 시저의 UDF를 사용하는 것이 좋습니다.

+0

이 정보를 제공해 주셔서 감사합니다. ExecuteScalar()! = null; – john

+1

그러면 불리언 값이 평가되고 invoiceExists 변수에 할당됩니다. –

0

예외는 가능성이 try 문 내에서 발생하는 자사의 유일한 캐스팅을 고려 invoiceExists = (bool)command.ExecuteScalar();에 의해 발생이. 문제를 해결하려면 ExecuteScalar()의 반환 결과를 봐야합니다.

+0

내 DB에서 쿼리를 실행하면 "InvNumber"를 "12345"라는 값으로 반환하므로 값이 반환됩니다 – john

+1

@john - 둘 중 하나도 bool에 캐스팅 될 수 없습니다. 두 문자열 값. –

2
이 저장 프로 시저를 변경

.This은 논리에 결함이 귀하의 요구 사항

ALTER PROCEDURE [dbo].[InvoiceExhists] 
@ExpenseID int 
AS 
BEGIN 
if exists(select * Expenses where ExpID = @ExpenseID) 
select 1 
else 
select 0 
END 
+0

어떤 이유로 든이 코드는 결과가 없어도 1을 반환합니다. – john

+1

@john 누락 된 'from'을 선택에 넣었습니까 – Karthik

관련 문제