Invalid Cast Exception

Discussion in 'ASP .Net' started by Lammert, Jun 28, 2006.

  1. Lammert

    Lammert Guest

    Good afternoon,

    I have a very strange problem. When I execute the code below the
    program throws an InvalidCastException. When I debug the code I see
    e.Item.DataItem is an object from the type OrganisatieOnderdeel. When
    you read the additional you can see the types are the same. How can I
    solve this problem?

    Kinds regards,
    Lammert


    Code:
    protected void fvwContact_ItemDataBound(object sender,
    DataListItemEventArgs e)
    {
    ObjectDataSource ods = new ObjectDataSource();
    ods.TypeName = "BusinessLogicLayer.FunctieVervulling";
    ods.SelectMethod = "GetFunctieVervullingenById";

    // An exception of type 'System.InvalidCastException' occurred in this
    this line:
    OrganisatieOnderdeel oo =
    (OrganisatieOnderdeel)e.Item.DataItem;

    ods.SelectParameters.Add("id", TypeCode.Int32,
    oo.Id.ToString());
    DataList ds = (DataList)e.Item.FindControl("dlPersonen");
    ds.DataSource = ods;
    ds.DataBind();
    }

    Message:
    An exception of type 'System.InvalidCastException' occurred in
    WebApp.DLL but was not handled in user code

    Additional information: Unable to cast object of type
    'BusinessLogicLayer.OrganisatieOnderdeel' to type
    'BusinessLogicLayer.OrganisatieOnderdeel'.
     
    Lammert, Jun 28, 2006
    #1
    1. Advertisements

  2. Lammert

    Lammert Guest

    This doesn't work. When I cast an Object (OrganisatieOnderdeel) to
    OrganisatieOnderdeel the program throws an InvalidCastException. For
    example e.Item.DataItem contains an Object of the type
    OrganisatieOnderdeel, but I can't cast this to OrganisatieOnderdeel!!
    Are there any solutions??

    Eliyahu Goldin schreef:
     
    Lammert, Jun 28, 2006
    #2
    1. Advertisements

  3. Lammert

    Lammert Guest

    Yes, I do!!

    Eliyahu Goldin schreef:
     
    Lammert, Jun 28, 2006
    #3
  4. Lammert,

    You have to filter out all non-data items with something like this:

    ListItemType itemType = e.Item.ItemType;

    if ((itemType == ListItemType.Pager) ||

    (itemType == ListItemType.Header) ||

    (itemType == ListItemType.Footer))

    {

    return;

    }



    Eliyahu
     
    Eliyahu Goldin, Jun 28, 2006
    #4
  5. Did you check in the debugger that e.Item.DataItem indeed is an object of
    the type
    OrganisatieOnderdeel?

    Eliyahu
     
    Eliyahu Goldin, Jun 28, 2006
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.