데이터베이스에 연결하고 주어진 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();
}
코드를 디버깅 했습니까? 'reader.Get..' 값이 매개 변수 유형에 유효합니까? –
@Kuzgun 나는 심지어 내 질문에 "캐스팅 오류를 던지고있는 줄은 양쪽에 **있다." – Maattt
@ SonerGönül 나는 모든 올바른 데이터 유형이지만 내 코드를 디버깅했지만 시도 할 것입니다. Int32를 Int16으로 변경합니다. 코멘트 해 주셔서 감사합니다! – Maattt