Monday, February 21, 2011

How do I set the selected value in an ASP.NET Drop Down List?

I'm using an ASP.NET dropdown. I want to set the selected element using an ID (Id) which is stored in the DataValue field.

ddlTest.DataValueField = "Id";    
ddlTest.DataTextField = "Name";
ddlTest.DataSource = searchResultList;
ddlTest.DataBind();

But all I can see is the SelectedIndex property which isn't the correct thing. How do I set by value?

From stackoverflow
  • After it's bound you can set the SelectedValue property to the correct id.

  • If you need the text of the selected item then you can use

    dropdwonlistID.SelectedItem.Value // selecting value of the selected item
    dropdwonlistID.SelectedItem.Text // selecting displayed text of the selected item
    
  • ddlTest.selectedValue = [whatever value you want to set];

0 comments:

Post a Comment