问题描述
我正在写,然后修补由几个人多年来的老项目。在一些地方,他们已经使用SelectedValue属性和其他地方,他们使用SelectedItem.Value。
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 SelectedItem.Value.
问:是的SelectedValue
短短的语法糖的的 SelectedItem.Value
或的SelectedValue
的工作方式不同引擎盖下?哪一个性能更好?
Question: Is SelectedValue
just a syntactic sugar for SelectedItem.Value
or SelectedValue
works differently under the hood? Which one performs better?
编辑: SelectedItem.Text被替换为SelectedItem.Value
SelectedItem.Text was replaced with SelectedItem.Value
推荐答案
的SelectedValue
返回相同的值 SelectedItem.Value
。
SelectedItem.Value
和 SelectedItem.Text
可能有不同的价值观和表现不是的Fator在这里,只这些性能问题的含义。
SelectedItem.Value
and SelectedItem.Text
might have different values and the performance is not a fator 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>
在这里 ddlUserTypes.SelecteItem.Value == ddlUserTypes.SelectedValue
无一不给1
ddlUserTypes.SelectedItem.Text
是管理员,这不同于 ddlUserTypes.SelectedValue
ddlUserTypes.SelectedItem.Text
is "Admins", which is different from ddlUserTypes.SelectedValue
修改
在引擎盖下,的SelectedValue看起来像这样
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;
}
}
和的SelectedItem看起来是这样的:
and SelectedItem looks like this:
public virtual ListItem SelectedItem
{
get
{
int selectedIndex = this.SelectedIndex;
if (selectedIndex >= 0)
{
return this.Items[selectedIndex];
}
return null;
}
}
这两个属性之间的一个主要区别是,的SelectedValue
有一个二传也,因为的SelectedItem
不。 的SelectedValue
的吸气剂是快写code时使用和执行性能问题并没有真正的理由进行讨论。同样的SelectedValue的一大优点是使用绑定EX pressions时。
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 to be used 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.
修改数据绑定方案(不能使用SelectedItem.Value)
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>
这篇关于的SelectedValue VS的DropDownList的SelectedItem.Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!