查看 RadioButtonList 是否具有选定值的最佳方法是什么?
我正在使用:
if (RadioButtonList_VolunteerType.SelectedItem != null)
或怎么样:
if (RadioButtonList_VolunteerType.Index >= 0)
或怎么样(根据安德鲁·黑尔的回答):
if (RadioButtonList_VolunteerType.Index > -1)
对于那些可能阅读此问题的人,以下不是有效的方法。 正如 Keltex 指出的,所选值可以是空字符串。
if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))
I am using:
if (RadioButtonList_VolunteerType.SelectedItem != null)
or how about:
if (RadioButtonList_VolunteerType.Index >= 0)
or how about (per Andrew Hare's answer):
if (RadioButtonList_VolunteerType.Index > -1)
To those who may read this question, the following is not a valid method. As Keltex pointed out, the selected value could be an empty string.
if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这些都是检查选定值的有效且完全合法的方法。 我个人认为
是最清楚的。
Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find
to be the clearest.
就可读性而言,它们对我来说都缺乏一些东西。 这似乎是扩展方法的一个很好的候选者。
In terms of readability they all lack something for me. This seems like a good candidate for an extension method.
问题更多地围绕是否检查 null 或检查 int 值。 Martin 伟大的扩展方法也可以这样写:
ListControl 的 MSDN 文档指出:
所以这两种方法都是有效的,而且都有效。 问题是哪一个是最好的方法。 我猜测 SelectedIndex 因为它是值类型操作而不是引用类型操作。 但我没有任何东西可以支持这一点。
The question revolves more around whether to check for null or check value of an int. Martin's great extension method could also be written:
The MSDN documentation for a ListControl states:
So either are valid ways and both work. The question is which is the best way. I'm guessing SelectedIndex as it is a value type operation rather than reference type operation. But I don't have anything to back that up with.
我建议:
根据 Microsoft 文档:
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) 并不总是有效,因为您可以拥有一个具有空值的 ListItem:
I recommend:
According to the Microsoft Documentation:
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) will not always work as you can have a ListItem with an empty value: