2014-03-04 7 views
1

데이터베이스에 연결하고 주어진 AccountNo (테이블의 필드)에 대한 정보 ("트랜잭션"테이블)를 검색하는 응용 프로그램이 있습니다. 그런 다음 검색된 정보를 "Transaction"클래스의 인스턴스에 넣습니다. 그런 다음 클래스의 인스턴스에서 미리 작성된 Generic Doubly Linked List ("트랜잭션")에 새 노드를 만듭니다. (내가 잘못한 말을 한 경우 사과하겠습니다.이 모든 것에 매우 익숙합니다.)InvalidCastException : 지정된 캐스트가 유효하지 않습니다?

내 문제는 검색된 정보를 "트랜잭션"클래스의 인스턴스에 넣으려고 할 때 "InvalidCastException ""지정한 캐스트가 유효하지 않습니다 "라고 표시됩니다. 모든 데이터 유형이 정확하므로 문제가 무엇인지 알지 못합니다.

여기 내 코드입니다.

트랜잭션 클래스 :

public class Transaction 
{ 
    private int AccountNumber; 
    private DateTime Date; 
    private string Description; 
    private string DebitCredit; 
    private float Amount; 

    public Transaction(int accountNumber, DateTime date, string description, string debitCredit, float amount) 
    { 
     this.AccountNumber = accountNumber; 
     this.Date = date; 
     this.Description = description; 
     this.DebitCredit = debitCredit; 
     this.Amount = amount; 
    } 
} 

내 코드의 나머지는 (그것의 양쪽에있는 캐스트 오류가 던지고 라인 **) 버튼을 클릭 이벤트 뒤에 :

private void button1_Click(object sender, EventArgs e) 
{ 
    LinkedList<Transaction> Transactions = new LinkedList<Transaction>(); //create the generic linked list 
    SqlConnection con = new SqlConnection(@"Data Source=melss002; Initial Catalog=30001622; Integrated Security=True"); //Connection string 
    int accNum = Int32.Parse(Microsoft.VisualBasic.Interaction.InputBox("Please enter account number", "Account Number")); //Prompt the user for account number 
    SqlCommand cmd = new SqlCommand("Select * From Transactions where AccountNo = " + accNum, con); //command to execute 
    con.Open(); //open the connection to the database   
    SqlDataReader reader = cmd.ExecuteReader(); 

    if (reader.HasRows)//Check if the table has records 
    { 
     while (reader.Read()) //read all records with the given AccountNo 
     { 
      **Transaction Transaction001 = new Transaction(reader.GetInt32(0), reader.GetDateTime(1), reader.GetString(2), reader.GetString(3), reader.GetFloat(4));** //New Transaction node 
      Transactions.AddFirst(Transaction001);// add the node to the Doubly Linked List (Transactions) 
     } 
    } 
    else 
    { 
     MessageBox.Show("No records found"); 
    } 

    PrintNodes(Transactions); 

    reader.Close(); 
    con.Close(); 
} 
+0

코드를 디버깅 했습니까? 'reader.Get..' 값이 매개 변수 유형에 유효합니까? –

+0

@Kuzgun 나는 심지어 내 질문에 "캐스팅 오류를 던지고있는 줄은 양쪽에 **있다." – Maattt

+0

@ SonerGönül 나는 모든 올바른 데이터 유형이지만 내 코드를 디버깅했지만 시도 할 것입니다. Int32를 Int16으로 변경합니다. 코멘트 해 주셔서 감사합니다! – Maattt

답변

2

, 그들은하지 않습니다 :이 라인을 보면

, 당신은 명시 적으로 지정된 데이터 형식의 필드를 반환하는 독자에게 :

Transaction Transaction001 = new Transaction(reader.GetInt32(0), reader.GetDateTime(1), reader.GetString(2), reader.GetString(3), reader.GetFloat(4)); 

해당 필드 0이 실제로 Int32 아닌 Int16 있는지 확인하고 해당 필드 4는 실제로 float 아닌 double 심지어 decimal입니다하시기 바랍니다. Decimal types은 대부분 에러의 원인이며, GetFloat에서 GetDouble으로 변경하여 문제를 해결할 수 있습니다.

+0

필드가 플로트인지 확신하기 때문에 플로트가 문제가되지 않습니다. 내 Int32를 Int16으로 변경하려고합니다. 답변 주셔서 감사합니다! – Maattt

+0

당신은 이것을 읽어야합니다 : http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx –

+1

그래, Visual Studio에서 SQL의 float가 double인가? GetFloat를 GetDouble로 변경 했으므로 대단히 감사합니다! – Maattt

0

테이블에 null 값이 있으면 이런 일이 발생할 수 있습니다. 예를 들어, amout가 null의 경우, float로 변환 할 수 없습니다. 또는 데이터베이스에 두 배가 될 수도 있고 실수하지 않을 수도 있습니다. 모든 데이터 유형이 오류 메시지가 얻을 수 없겠죠 정확 경우

관련 문제