Monday, 12 April 2010

ASP.NET: Reset Selected Value of AJAX Combo Box

I have been banging my head off my desk for hours and hours, trying to find a way to reset the value of an ASP.NET Control Toolkit Combo Box.

Fundamentally it's a brilliant control and lends some superb ease of use to an application when applied properly, but for some reason it's lacking a straightforward and functional way to reset its value to a default of something like:

<asp:ListItem Value="0"> -- Select -- </asp:ListItem>

I tried various combination of these, plus messing about with the AppendDataBoundItems property and the ViewState setting:

ComboBoxSelector.SelectedIndex = -1
ComboBoxSelector.SelectedIndex = 0

Those are not important, the thing to note is that using any of the above will not actually reset the value of the Combo Box.

To reset it, you have to loop through the hidden controls that are created at runtime, and reset those to the default value:

Dim ctl As Control
For Each ctl In ComboBoxAllKeywordCategories.Controls
If TypeOf ctl Is HiddenField Then
CType(ctl, HiddenField).Value = "0"
End If

This works, and resets the Combo back to the default value you want. I no longer feel the need to put my fist through my monitor, so, result.


Phil said...

Or, just do ComboBox.ClearSelection()