r0bb077
r0bb077

Reputation: 752

Unable to cast object of Sytem.String to type

I'm receiving this messaage;

Unable to cast object of type 'System.String' to type 'main.Entitys.Department'.

for this piece of code;

return ((Department)department_ComboBox.SelectedItem).ToInt();

I have a combobox with many Department objects within it, and i'm trying to retrieve the ID of the selected item using this method within the Department class;

public int ToInt()
    {
        return dID;
    }

I don't get why it's saying it can't cast a string object when I'm trying to return an int?!

Upvotes: 0

Views: 211

Answers (2)

Lukas
Lukas

Reputation: 2923

I'm missing some pieces there, but if all you want to do is return an int, assuming the department_ComboBox.SelectedItem is an integer, just conver it or cast it. To conver it, simply do

Convert.toInt32(department_ComboBox.SelectedItem);

Upvotes: -1

Hector Sanchez
Hector Sanchez

Reputation: 2317

(Department)department_ComboBox.SelectedItem // Here is the Mistake

The selectedItem is String check it, it is NOT a Department.

Upvotes: 3

Related Questions