SelectedValue vs SelectedItem.Value of DropDownList

后端 未结 5 1771
猫巷女王i
猫巷女王i 2020-12-08 09:37

I\'m working on an old project written and then patched by several people over the years. At some places they have used SelectedValue property and other places they used Sel

5条回答
  •  心在旅途
    2020-12-08 10:25

    SelectedValue returns the same value as SelectedItem.Value.

    SelectedItem.Value and SelectedItem.Text might have different values and the performance is not a factor here, only the meanings of these properties matters.

    
        
        
    
    

    Here, ddlUserTypes.SelectedItem.Value == ddlUserTypes.SelectedValue and both would return the value "1".

    ddlUserTypes.SelectedItem.Text would return "Admins", which is different from ddlUserTypes.SelectedValue

    edit

    under the hood, SelectedValue looks like this

    public virtual string SelectedValue
    {
        get
        {
            int selectedIndex = this.SelectedIndex;
            if (selectedIndex >= 0)
            {
                return this.Items[selectedIndex].Value;
            }
            return string.Empty;
        }
    }
    

    and SelectedItem looks like this:

    public virtual ListItem SelectedItem
    {
        get
        {
            int selectedIndex = this.SelectedIndex;
            if (selectedIndex >= 0)
            {
                return this.Items[selectedIndex];
            }
            return null;
        }
    }
    

    One major difference between these two properties is that the SelectedValue has a setter also, since SelectedItem doesn't. The getter of SelectedValue is faster when writing code, and the problem of execution performance has no real reason to be discussed. Also a big advantage of SelectedValue is when using Binding expressions.

    edit data binding scenario (you can't use SelectedItem.Value)

    
     
         
         
     
    
    

提交回复
热议问题