Workaround for ASP.NET AjaxControlToolkit Combo Box issue

Problem ComboBox is one of the exotic controls present in AjaxControlToolkit . But I have come across some problems while using it. They are :

After clearing all the items of Combo Box , the selected item does not get cleared , even after post back.

Sometimes after binding the data , Combo box is not displaying the first item or It remains blank or It will be displayed only when we move in/out focus in the combo box.

Solution

Before going to the solution , first we need to know – that Ajax Combo box uses hidden field for storing the selected index .

So whenever we clear the combo box item by : comboSelectCity.Items.Clear(); even Followed by comboSelectCity.SelectedValue = String.Empty; would not clear the selected value in combobox , As value is contained in hidden field .

So , on clearing/resetting the hidden field associated with combobox can do the work.

Implementation

Let us create a method :

private void ClearCombobox(AjaxControlToolkit.ComboBox comboBox)
    {
          comboBox.ClearSelection();
           foreach (Control control in comboBox.Controls)
          {
                 if (control is HiddenField)
             //Set the hidden field value to 0 to always point first item.
                 ((HiddenField)control).Value = "0";
            }
    }

Here we found the hidden field associated with particular combo box and set it to first item of the control (no matter whether first item exists or not)

So now whenever we want to clear the items of Combobox. We can write :

comboCity.Items.Clear();
ClearComboBox(comboCity);
Or before binding


comboCity.Items.Clear();
ClearComboBox(comboCity);
comboCity.DataSource = dtCityList; // dtCityList is a data source
comboCity.DataBind();

Conclusion

After fixing this problem AjaxControlToolkit ComboBox is now working fine . But if you are  using the combobox item in your page , you can also look through other technologies, like jQuery plugins; they are light weight and less error prone.

References

http://vincexu.blogspot.com/2009/06/about-ajaxcontroltoolkit-combobox.html

You can find another solution,here http://forums.asp.net/p/1477260/3437991.aspx

150 150 Burnignorance | Where Minds Meet And Sparks Fly!