Configuring SelectedValue Data DropDownList

I have an asp.net dropDownList that is automatically bound to sqlDataSource to client type values ​​when the page loads. When the page loads, I also create a Client object, one of its properties is ClientType. I am trying to set SelectedValue from ddl according to the value of the ClientType property of the Client object unsuccessfully. I get the following error "System.ArgumentOutOfRangeException:" ddlClientType "has a SelectedValue value, which is invalid because it does not exist in the list of items." I understand that this is because the list is not yet populated when I try to set the selected value. Is there any way to overcome this problem? Thank!

+5
source share
2 answers

You should use the DataBound event, it will be fired, after the data binding is completed

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 method DataBind()before setting the value ...

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

Before setting the selected value, check whether the item is in the list and what it is selected 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 linking to the Load page, try to follow this path:

  • Move all binding related code in overriden method DataBind()
  • Page_Load : ( DataBind , )
if (!IsPostBack)
{
   Page.DataBind(); // only for pages
}
+4

All Articles