查看RadioButtonList是否具有选定值的最佳方法是什么?
我在用:
if (RadioButtonList_VolunteerType.SelectedItem != null)
或怎么样:
if (RadioButtonList_VolunteerType.Index >= 0)
或者怎么样(根据Andrew Hare的回答):
if (RadioButtonList_VolunteerType.Index > -1)
对于那些可能阅读此问题的人, 以下不是有效的方法 。 正如Keltex指出的那样,所选值可能是一个空字符串。
if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))
在可读性方面,他们都缺乏一些东西。 这似乎是扩展方法的一个很好的候选者。
public static class MyExtenstionMethods { public static bool HasSelectedValue(this RadioButtonList list) { return list.SelectedItem != null; } } ... if (RadioButtonList_VolunteerType.HasSelectedValue) { // do stuff }
这些都是检查所选值的有效且完全合法的方法。 我个人觉得
RadioButtonList_VolunteerType.SelectedIndex > -1
是最清楚的。
我建议:
RadioButtonList_VolunteerType.SelectedIndex>=0.
根据Microsoft文档 :
列表中所选项目的最低序数索引。 默认值为-1,表示未选择任何内容。
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) 并不总是有效,因为你可以有一个空值的ListItem:
This item has no value
问题更多地围绕是检查null还是检查int的值。 马丁的伟大扩展方法也可以写成:
public static bool HasSelectedValue(this ListControl list) { return list.SelectedIndex >= 0; }
ListControl的MSDN文档说明:
SelectedItem的默认值为null 。
SelectedIndex的默认值为-1 。
所以要么是有效的方式,要么都有效。 问题是哪种方法最好。 我猜测SelectedIndex,因为它是一个值类型操作而不是引用类型操作。 但我没有任何东西支持这一点。