ASP.NET: Why does ListControl.Text return the *val

2020-07-30 02:14发布

List controls deriving from ListControl, such as DropDownList, ListBox or RadioButtonList, are populated by a list of ListItems. A ListItem has a Value and a Text property.

ListControl offers the following methods to access the currently selected item:

  • ListControl.SelectedItem returns the currently selected ListItem,
  • ListControl.SelectedValue returns the Value property of the currently selected ListItem.

Now, the interesting thing is:

  • ListControl.Text returns exactly the same value as ListControl.SelectedValue. It does not return SelectedItem.Text, as one might expect.

This is by design:

ListControl.Text Property

Gets or sets the SelectedValue property of the ListControl control.

[...]

Remarks

The Text property gets and sets the same value that the SelectedValue property does.

This seems counter-intuitive and confuses people. My question is: Why was it done this way? I can imagine that providing a Text property is necessary for implementing the ITextControl interface, but why on earth would you choose to have it return the Value of the ListItem rather than the Text?

2条回答
甜甜的少女心
2楼-- · 2020-07-30 02:49

I checked that out before using .NET Reflector. If ListItem.Text is null, it returns ListItem.Value instead; if that is null, it returns an empty string. It works in vice versa for ListItem.Value too. So it's not the ListControl doing this, it's selected item itself.

HTH.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-30 02:49

If the code used to process an ASPX page defines all controls using the ITextControl interface, the Text property is the only property available. When processing a ListControl, most of the business logic I write cares about the value of the selected item, not the text. Thus, in my opinion, the current behavior is the desired behavior, even if it is not necessarily the expected behavior.

查看更多
登录 后发表回答