Setting SelectedValue of a data bound DropDownList
Asked Answered
T

2

5

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!

Tachylyte answered 19/7, 2011 at 11:57 Comment(0)
P
6

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";
}
Prewar answered 19/7, 2011 at 12:7 Comment(2)
I tried again using the dataBound event and I no longer recieve the error message but the value isn't selected.Tachylyte
I had tried your second suggestion before using also ddl.DataSourceID="" & it didn't work. I tried again without the DataSourceID. I had other issues such as trailing blank spaces in the data and after trimming it finally worked. Thank you.Tachylyte
F
4

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
}
Fatso answered 19/7, 2011 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.