InvalidCastException:指定的强制转换无效?

时间:2014-03-04 08:00:30

标签: c# class doubly-linked-list

我有一个连接到数据库的应用程序,并为给定的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();
}

2 个答案:

答案 0 :(得分: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甚至是{{ 1}}。在大多数情况下,十进制类型是错误的来源,我敢打赌,您可以通过从decimal更改为GetFloat来解决问题。

答案 1 :(得分:0)

如果表中有空值,则可能发生这种情况。例如,如果amount为null,则无法转换为float。或者它可能是数据库的两倍,而不是浮动。