Dov Miller
Dov Miller

Reputation: 2058

Setting SelectedValue of a data bound DropDownList

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!

Upvotes: 5

Views: 19454

Answers (2)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

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";
}

Upvotes: 6

sll
sll

Reputation: 62484

Before setting a selected value check whether item is in list and than select it by index

<asp:DropDownList id="dropDownList"
                    AutoPostBack="True"
                    OnDataBound="OnListDataBound"
                    runat="server />
protected void OnListDataBound(object sender, EventArgs e) 
{
    int itemIndex = dropDownList.Items.IndexOf(itemToSelect);
    if (itemIndex >= 0)
    {
      dropDownList.SelectedItemIndex = itemIndex;
    }
}

EDIT: Added...

If you are doing binding stuff in Page Load, try to follow this way:

  • Move all binding related code in overriden DataBind() method
  • In Page_Load of Page add: (in case of control do not call DataBind directrly, this is a responsibility of a parent page)
if (!IsPostBack)
{
   Page.DataBind(); // only for pages
}

Upvotes: 4

Related Questions