下拉列表的value和text属性可以独立使用吗?
ASP.NET 中下拉列表的这两个属性可以独立使用吗?
我想在用户选择某些文本时检索 null
值;我不能,因为每当 Value
为 null
时它都会检索 Text
属性。例如:
l1 = new ListItem("Cat", null);
Console.WriteLine(l1.Value);
输出是
猫
在另一种情况下,当两个属性具有不同的字符串时,当我使用 Text
属性时,我会在 Value
属性中获取字符串。例如:
l2 = new ListItem("Cat", "Mouse");
DropDownList ddl = new DropDownList();
ddl.Items.Add(li);
ddl.SelectedIndex = 0;
Console.WriteLine(ddl.SelectedValue);
Console.WriteLine(ddl.Text);
输出是
鼠标
鼠标
Can these two properties of a dropdown list in ASP.NET be used independently?
I wanted to retrieve a null
value when the user selects some text; I couldn't as it retrieves the Text
property whenever the Value
is null
. Eg:
l1 = new ListItem("Cat", null);
Console.WriteLine(l1.Value);
The output is
Cat
In another situation, when both the properties have different strings, I get the string in the Value
property when I use the Text
property. Eg:
l2 = new ListItem("Cat", "Mouse");
DropDownList ddl = new DropDownList();
ddl.Items.Add(li);
ddl.SelectedIndex = 0;
Console.WriteLine(ddl.SelectedValue);
Console.WriteLine(ddl.Text);
The output is
Mouse
Mouse
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的观察是正确的。与直觉告诉我们的相反,
ListControl.Text
(以及DropDownList.Text
)不返回TextListItem
的 code> 属性。以下是文档的摘录:要获取所选
ListItem
的Text
属性,请使用SelectedItem
检索当前所选列表项,然后访问Text属性。
因此,您所看到的行为是设计使然的。为什么.NET 开发人员以如此不直观的方式指定
ListControl.Text
?我不知道。也许有必要支持ITextControl
接口......Your observation is correct. Contrary to what intuition tells us,
ListControl.Text
(and, thus,DropDownList.Text
) does not return theText
property of the currently selectedListItem
. Here's an excerpt from the documentation:To get the
Text
property of the selectedListItem
, useSelectedItem
to retrieve the currently selected list item and then access theText
property.So, the behavior you are seeing is by design. Why did the .NET developers specify
ListControl.Text
in such an unintuitive way? I have no idea. Maybe it was necessary to support theITextControl
interface...只需将该值设置为一些哨兵值,例如空字符串或一些疯狂的字符串“JANDKJASD_”并进行相应的处理。
Just set the value to some sentinel value like an empty string or some crazy string "JANDKJASD_" and handle it accordingly.