none
DropDownList.SelectedValue Vs DropDownList.Items.FindByValue("").Selected = true ??

    Question

  • Hi all. Good day
    My question is that what is the usual practice to make an item selected in a DropDownList?
    I've seen issues regarding both the techniques. When we assign a value using "DropDownList.SelectedValue", and when if the assigned value has no item in the DropDownList, it gives an exception.
    Now in case of  DropDownList.Items.FindByValue("").Selected = true, we can have a check if the DropDownList.Items.FindByValue("") != null, But by selecting an item usign this, gives the exception of "Can not have multiple items selected in the DropDownList" although i am also doing DropDownList.ClearSelection(), just before selection.
    Please guide me in this case, and also tell me what is the usual practice of selecting an item from the dropdown based on its value or text?

    Thanks.
    • Moved by Harry Zhu Thursday, July 16, 2009 5:58 AM relating to dropdownlist (From:Visual C# Language)
    Wednesday, July 15, 2009 3:37 AM

Answers

  • hi,

    You can do bit of both the approach.

    ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
    if(oListItem != null)
    DropDownList1.SelectedValue = oListItem.Value;

    Regards,
    Vinil
    • Marked as answer by Kira Qian Tuesday, July 21, 2009 6:12 AM
    Wednesday, July 15, 2009 5:30 AM

All replies

  • hi,

    You can do bit of both the approach.

    ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
    if(oListItem != null)
    DropDownList1.SelectedValue = oListItem.Value;

    Regards,
    Vinil
    • Marked as answer by Kira Qian Tuesday, July 21, 2009 6:12 AM
    Wednesday, July 15, 2009 5:30 AM
  • Yeah thats what i m doing at the moment, becuase i dont see any other way of escaping from both of these exceptions. But i want to know what the geeks use to make it selected, and how do they do it?
    Wednesday, July 15, 2009 10:59 AM
  • I used the code

    ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
    if(oListItem != null)
    DropDownList1.SelectedValue = oListItem.Value;

    to get the text by sending the value,but it doesn't work. Is this code only used to get the value?

    Please let me know.
    Tuesday, October 20, 2009 11:48 PM
  • Which text you want to get? if its the text of ListItem then you can do "oListItem.Text" simply.

    This specific code snippet is for selecting the item which contains the same value as "yourValue". Before selecting it, it looks whether that item exists in the dropdownlist or not

    Please mark the post as Answer/ Helpful, if it helps you.
    Wednesday, October 21, 2009 3:55 AM
  • Thx Very much
    Tuesday, November 23, 2010 8:46 AM