简体   繁体   中英

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

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.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM