Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So, I've been continously working on my little project with more or less success but find myself in front of a problem I seemingly can't solve on my own. I get thrown an InvalidCastException when I'm basically just reusing a function that works already.

What I have tried:

var c = (customerDB)comboBox1.SelectedItem;
newContact.Name = textBox_Contact_Name.Text.Trim();
newContact.Vorname = textbox_Contact_Firstname.Text.Trim();
newContact.FKKunde = c.PKCustomer;

db.Contacts.Add(newContact);
db.SaveChanges();
Close();

The above code is the snippet that works, below is the one that doesn't.
var b = (TArticle)comboBox_Article.SelectedItem;
TPosition newPosition = new TPosition();


newPosition.FKArticle = b.PKArticle;
newPosition.Quantity = (int)numericUpDown_Menge.Value;
newPosition.Position = textBox_Position.Text;
db.TPosition.Add(newPosition);
db.SaveChanges();
Close();

It seems like the same to me, yet the second one doesn't run properly. The exception is thrown when declaring var b.
Posted
Updated 8-May-18 0:04am
Comments
Maciej Los 8-May-18 4:36am    
Check what type of object is stored in comboBox_Article.SelectedItem.
var b = comboBox_Article.SelectedItem;
if(typeof(TArticle)==b.GetType())
{
    //further instructions
}

I'm pretty sure that comboBox_Article.SelectedItem is type of object (or null).

The item in the ComboBox is an instance of a customerDB in the first case, but it isn't an instance of a TArticle or a class derived from TArticle in the second. If the instance is of a class that cannot be cast to the required type, you will get an invalid cast exception.

Start by using the debugger to find out exactly what the selected item actually is: when you know that, you can start looking at why it isn't what you thought it was, or work out what class you should be converting it to.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900