Setting SelectedValue of a data bound DropDownList

Dov Miller picture Dov Miller · Jul 19, 2011 · Viewed 18.5k times · Source

I have an asp.net dropDownList which is automatically bound to a sqlDataSource to values of client type on page load. On page load I am also creating a Client object, one of it's properties is ClientType. I am trying to set the SelectedValue of the ddl according to the value of the ClientType property of the Client object unsuccessfully. I recieve the following error message "System.ArgumentOutOfRangeException: 'ddlClientType' has a SelectedValue which is invalid because it does not exist in the list of items". I understand that this is because the list has not yet been populated when I'm trying to set the selected value. Is there a way of overcoming this problem? Thank you!

Answer

Muhammad Akhtar picture Muhammad Akhtar · Jul 19, 2011

You have to use the DataBound Event, it will be fired, once databinding is complete

protected void DropDownList1_DataBound(object sender, EventArgs e)
{
    // You need to set the Selected value here...
}

If you really want to see the value in the Page load event, then call the DataBind() method before setting the value...

protected void Page_Load(object sender, EventArgs e)
{
    DropdownList1.DataBind();
    DropdownList1.SelectedValue = "Value";
}