指定的强制转换无效#3
本文关键字:转换 无效 | 更新日期: 2023-09-27 17:57:26
我遇到这个问题,因为我在Visual Studio内部的错误列表中收到"指定的强制转换无效"无错误。这个错误可能来自我的Access数据库吗?
private void Submit_Click(object sender, EventArgs e)
{
String desItem = desWork.Text;
decimal partscost = Convert.ToDecimal(textBoxPartsCost.Text);
decimal laborhours = Convert.ToDecimal(textBoxHours.Text);
decimal laborrate = Convert.ToDecimal(textBoxRate.Text);
decimal total = laborhours * laborrate + partscost;
try
{
servicesTableAdapter.InsertServices((short?)comboBoxCustomer.SelectedValue, (DateTime?)dateTimePickerServiceDate.Value, desItem, partscost, laborhours, laborrate, total);
MessageBox.Show("Services Inserted", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我认为它可能来自(short?)comboBoxCustomer.SelectedValue
,因为在Visual Studio中,它告诉我需要转换为短整数,但在Access中,我使用的是长整数。不知道为什么会这样。有人能告诉我我做错了什么吗?
你的猜想几乎可以肯定是正确的。
装箱的值类型只能被取消装箱到其实际类型。如果你有一个long
,你不能直接将它取消框为short?
。您必须先将其取消框为long
(或long?
),然后将其转换为short?
。
这是一个经常被问到的问题。请参阅我关于这个主题的文章以获得详细的解释。
http://ericlippert.com/2009/03/03/representation-and-identity/