System.InvalidCastException with UserControl and comboBox

  • Thread starter Thread starter bob scola
  • Start date Start date
B

bob scola

I have a csharp, VS 2003 solution for a winform application
The application uses an object called a "matter" and the class is
defined in matter.cs.

I can load matter objects into a combobox


Matter[] matters= v.Matters;
comboBox1.Items.AddRange(matters);


And I can fetch the matter object after a selection:

private void comboBox1_SelectedIndexChanged(object sender,
System.EventArgs e)

{
Matter m;
m= (Matter) comboBox1.SelectedItem;
Debug.WriteLine(m.GetType().ToString()); // --> MIDE.Matter
Debug.WriteLine(m.Name); // this works ok
Debug.WriteLine(m.ID); // this works ok
}

All is working well-


Now I want a UserControl which also has a combobox which is loaded
with a set of Matters.
I add a new project in the solution for my UserControl & I ctrl-drag
matter.cs into the UserControl's solution.

In my UserControl, I can populate & display the combox fine, but when
I go to fetch the object out of it, I get a
System.InvalidCastException.
Note that I can get the object from the combobox as an object, the
object tells me it the proper type, and I can run the objects
ToString() fine, but my cast is dying.


in the user control --



private void cboMatterName_SelectedIndexChanged(object sender,
System.EventArgs e)

{
object o;
o= cboMatterName.SelectedItem;

Debug.WriteLine(o.GetType().ToString()); // --> MIDE.Matter
Debug.WriteLine(o.ToString()); // This works ok

Matter m;

// *** this throws a System.InvalidCastException ***
m= (Matter) cboMatterName.SelectedItem;

}



Any ideas?

thanx
Bob
 
Check SelectedItem.GetType().GUID against typeof(Matter).GUID before the
cast that throws the exception. Are they the same?

If your projects are referencing each other, it may be that your ComboBox
has Matter objects from one project, however you are casting it to a Matter
from the UserControl project. This would cause your InvalidCastException.

Regards,
Matt
 
Back
Top