【发布时间】:2014-04-05 15:27:10
【问题描述】:
我有一个应用程序,它连接到数据库并检索给定 AccountNo(表中的一个字段)的信息(从名为“Transactions”的表中)。然后它将检索到的信息放入一个名为“Transaction”的类的实例中。然后从该类的实例中创建一个新节点到预先创建的通用双向链接列表中,称为“事务”。 (如果我措辞有误,我深表歉意,我对这一切都很陌生)
现在我的问题是,当我尝试将检索到的信息放入“事务”类的实例中时,我得到一个“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 我做到了,我什至在我的问题中说“抛出投射错误的行的两边都有 **”
-
@SonerGönül 我已经调试了我的代码,我确信它们都是正确的数据类型,但我会尝试将 Int32 更改为 Int16。谢谢你的评论!
-
尽量不要转换值并将它们放在
object中,然后在调试器中检查对象。 -
@Maattt 我很确定您只是认为您会得到一个
float,因为在数据库中,列类型是FLOAT- 但是在一个FLOATSQL 映射到 C# 中的double。请参阅我在对我的问题的评论中发布的链接。
标签: c# class doubly-linked-list