Selecting An Old Value While Binding a DropDownList
I had a usual instance where a DropDownList was bound to a table in a database. However, that list of data could change in the database without regard to those values having been previously stored (as text, not IDs, unfortunately) in another table. Meaning that when the DropDownList would now be loaded with the newly updated data, the previously selected value would not have a corresponding choice in the drop down anymore.
The DropDownList doesn’t take too kindly to this and gives an ArgumentOutOfRangeException error. But I needed that old value as a possible choice in the dropdown still, as well as the new choices.
The problem was that I needed to get the saved value from the database (which failed to be the initial SelectedValue). So I just stored it in the ToolTip for the DropDownList, then I could retrieve it and update it from anywhere.
Note: Be sure to use OnDataBinding not OnDataBound to add the new item.
<asp:DropDownList ID=”HotelNameDropDown” runat=”Server” DataSourceID=”ObjectDataSource1″
SelectedValue=’<%# Bind(“HotelName”) %>‘ AppendDataBoundItems=”true”
OnDataBinding=”HotelNameDropDown_OnDataBinding” ToolTip=’<%# Bind(“HotelName”) %>‘
OnSelectedIndexChanged=”HotelNameDropDown_OnSelectedIndexChanged”
DataTextField=”HotelName” DataValueField=”HotelName” />
Depending on when you postback, you might also need to update the ToolTip when the user changes the DropDownList.
protected void HotelNameDropDown_OnSelectedIndexChanged(object sender, EventArgs e)
{
// Set the tooltip to the selected value onchange, becuase we will use the tooltip below
DropDownList ddl = (DropDownList)sender;
ddl.ToolTip = ddl.SelectedValue;
}
Here I try to bind the DropDownList with the data, if this fails then it creates a new ListItem at the top of the list with a name and value of what we had stored in the ToolTip from the .aspx page.
protected void HotelNameDropDown_OnDataBinding(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.DataBinding -= new EventHandler(HotelNameDropDown_OnDataBinding);
try
{
ddl.AppendDataBoundItems = false;
ddl.DataBind();
ddl.SelectedValue = ddl.ToolTip;
}
catch(ArgumentOutOfRangeException)
{
ddl.Items.Clear();
ddl.AppendDataBoundItems = true;
ListItem li = new ListItem(ddl.ToolTip, ddl.ToolTip);
li.Selected = true;
ddl.Items.Insert(0, li);
}
}
More info about this topic can be found here: