locked
Type Cast Error RRS feed

  • Question

  • Hi,

    i am newibe in Entity Framework.I have a model. On this model , i have a table name Author.I have a dropdownlist. I am binding this dropdownlist with Authors name. I want to  fetch the authors name when i am going to change dropdownlist. In my dropdownlist selectedinexchanged  i wrote,

    Author selItem=(Author) dropdownlist1.selectedItem.

    How its possible.?

    Thanks and Regards,

    Dileep Sanker

    Tuesday, February 28, 2012 4:47 AM

Answers

  • You will need to get the Author object based (depending how you bound the list to the drop down list initially) either by selected index, value, or text.  For example,

    dropdownlist1.DataSource = authors.ToList();

    dropdownlist1.DataTextField = "Name";

    dropdownlist1.DataValueField = "ID";

    dropdownlist1.DataBind();

    //then

    Author a = from author in datacontext.tbAuthor

    where author.id == dropdownlist1.Value

    select author;

    • Proposed as answer by Allen_MSDN Friday, March 2, 2012 2:18 AM
    • Marked as answer by Allen_MSDN Monday, March 5, 2012 2:50 AM
    Wednesday, February 29, 2012 3:31 PM

All replies

  • Hi Dileep sankar,

    Welcome to MSDN Forum.

    You bind Author's name to a dropdownlist, but the name is only a property of Author entity, so you can't convert a string(I guess the name is a string type) variable to an Author type. If you want to get the name, just use a string variable to receive it is OK.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, February 29, 2012 3:03 AM
  • You will need to get the Author object based (depending how you bound the list to the drop down list initially) either by selected index, value, or text.  For example,

    dropdownlist1.DataSource = authors.ToList();

    dropdownlist1.DataTextField = "Name";

    dropdownlist1.DataValueField = "ID";

    dropdownlist1.DataBind();

    //then

    Author a = from author in datacontext.tbAuthor

    where author.id == dropdownlist1.Value

    select author;

    • Proposed as answer by Allen_MSDN Friday, March 2, 2012 2:18 AM
    • Marked as answer by Allen_MSDN Monday, March 5, 2012 2:50 AM
    Wednesday, February 29, 2012 3:31 PM