I use a RadDropDownList, I want to give the user the ability to search the items in the drop down so I use the default DropDownStyle = DropDown with AutoCompleteMode = SuggestAppend.
However, I want to ensure that the user selects a valid item from the list and doesn't leave random text. So I created the extension method EnsureValidSelection() below that remembers the original value, and on validation resets it to that original value if no valid value is now selected.
This works well when the ValueMember is an int. But when it's a string, it ignores the code that sets the SelectedValue.
public static void EnsureValidSelection(this RadDropDownList combo)
{
object originalValue = null;
combo.Enter += DropDownEnter;
combo.SelectedValueChanged += DropDownSelectedValueChanged;
combo.Validated += DropDownValidated;
return;
void DropDownEnter(object sender, EventArgs e)
{
originalValue = ((RadDropDownList)sender).SelectedValue;
}
void DropDownSelectedValueChanged(object sender, EventArgs e)
{
if (originalValue != null && combo.SelectedValue != null)
originalValue = combo.SelectedValue;
}
void DropDownValidated(object sender, EventArgs e)
{
if (combo.SelectedValue == null)
combo.SelectedValue = originalValue;
originalValue = null;
}
}