SelectedValue vs SelectedItem.Value of DropDownList
They are both different. SelectedValue
property gives you the actual value of the item in selection whereas SelectedItem.Text
gives you the display text. For example: you drop down may have an itme like
<asp:ListItem Text="German" Value="de"></asp:ListItem>
So, in this case SelectedValue
would be de
and SelectedItem.Text
would give 'German'
EDIT:
In that case, they aare both same ... Cause SelectedValue
will give you the value stored for current selected item in your dropdown and SelectedItem.Value
will be Value of the currently selected item.
So they both would give you the same result.
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.
<asp:DropDownList runat="server" ID="ddlUserTypes">
<asp:ListItem Text="Admins" Value="1" Selected="true" />
<asp:ListItem Text="Users" Value="2"/>
</asp:DropDownList>
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)
<asp:Repeater runat="server">
<ItemTemplate>
<asp:DropDownList ID="ddlCategories" runat="server"
SelectedValue='<%# Eval("CategoryId")%>'>
</asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.