Claude Grecea
Claude Grecea

Reputation: 543

Specified cast is not valid #3

I have this issue where I am receiving "Specified cast is not valid" no errors in the Error list inside Visual Studio. Could this error becoming from my Access Database?

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);
    }
}

I think it may be coming from the (short?)comboBoxCustomer.SelectedValue because inside Visual Studio it's telling me I need to cast into a short but inside Access I am using long integer. Not sure why this is the case. Can someone let me know what I am doing wrong?

Upvotes: 1

Views: 2569

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660088

Your conjecture is almost certainly correct.

A boxed value type may only be unboxed to the type it actually is. If you have a long in there, you can't unbox it to short? directly. You have to unbox it to long (or long?) first, and then convert it to short?.

This is a pretty frequently asked question. See my article on the subject for a detailed explanation.

http://ericlippert.com/2009/03/03/representation-and-identity/

Upvotes: 8

Related Questions