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

What's the difference between

DropDownList.ClearSelection();

and

DropDownList.SelectedIndex = -1;

while working with a dropdown list?

Edit: I know the definitions available for MSDN. Can someone explain the differences in implementation / practical use.

+4
source share
1 answer

To the source for System.Web.UI.WebControls.ListControlfrom which it is inferred DropdownList, it looks like the setting SelectedIndexactually calls ClearSelection(); and if not -1, it will go on 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: therefore, answering your question, the call ClearSelection()will directly save you from a few (non-essential) if statements.

+9
source

Source: https://habr.com/ru/post/1669663/


All Articles