Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between DropDownList.ClearSelection() and DropDownList.SelectedIndex=-1

Tags:

c#

asp.net

What is the difference between

DropDownList.ClearSelection();

and

DropDownList.SelectedIndex = -1;

while working with a dropdownlist?

Edit : I am aware of the definitions for these available at MSDN. Can someone provide differences in implementation/practical use.

like image 355
Prayag Sagar Avatar asked Jan 05 '23 13:01

Prayag Sagar


1 Answers

Looking into the source for System.Web.UI.WebControls.ListControl, from which DropdownList is derived, it seems like setting SelectedIndex actually calls ClearSelection(); and if not -1, it will proceed to select the item.

    public virtual void ClearSelection() {
        for (int i=0; i < Items.Count; i++)
            Items[i].Selected = false;
    }

    public virtual int SelectedIndex {
        set {
            ...
            if ((Items.Count != 0 && value < Items.Count) || value == -1) {
                ClearSelection();
                if (value >= 0) {
                    Items[value].Selected = true;
                }
            }
            ...
        }

Edit: so in answer to your question, calling ClearSelection() directly would save you from a couple of (inconsequential) if statements..

like image 179
NPras Avatar answered Jan 07 '23 03:01

NPras