C# 查看 RadioButtonList 是否具有选定值的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/735775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to see if a RadioButtonList has a selected value?
提问by John Bubriski
I am using:
我在用:
if (RadioButtonList_VolunteerType.SelectedItem != null)
or how about:
或者怎么样:
if (RadioButtonList_VolunteerType.Index >= 0)
or how about (per Andrew Hare's answer):
或者怎么样(根据 Andrew Hare 的回答):
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.
对于可能阅读此问题的人,以下不是有效方法。正如 Keltex 指出的那样,选定的值可能是一个空字符串。
if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))
采纳答案by Martin Clarke
In terms of readability they all lack something for me. This seems like a good candidate for an extension method.
就可读性而言,它们对我来说都缺乏一些东西。这似乎是扩展方法的一个很好的候选者。
public static class MyExtenstionMethods
{
public static bool HasSelectedValue(this RadioButtonList list)
{
return list.SelectedItem != null;
}
}
...
if (RadioButtonList_VolunteerType.HasSelectedValue)
{
// do stuff
}
回答by Andrew Hare
Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find
这些都是检查选定值的有效且完全合法的方法。个人觉得
RadioButtonList_VolunteerType.SelectedIndex > -1
to be the clearest.
要最清楚。
回答by Keltex
I recommend:
我建议:
RadioButtonList_VolunteerType.SelectedIndex>=0.
According to the Microsoft Documentation:
根据微软文档:
The lowest ordinal index of the selected items in the list. The default is -1, which indicates that nothing is selected.
列表中所选项目的最低序数索引。默认值为 -1,表示未选择任何内容。
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) will not always workas you can have a ListItem with an empty value:
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue)并不总是有效,因为您可以拥有一个空值的 ListItem:
<asp:ListItem Value=''>This item has no value</asp:ListItem>
回答by Scotty.NET
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:
问题更多地围绕是检查 null 还是检查 int 的值。Martin 伟大的扩展方法也可以写成:
public static bool HasSelectedValue(this ListControl list)
{
return list.SelectedIndex >= 0;
}
The MSDN documentation for a ListControl states:
ListControl 的 MSDN 文档指出:
Default for SelectedItem is null.
Default for SelectedIndex is -1.
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.
所以要么是有效的方法,要么都有效。问题是哪种方法最好。我猜 SelectedIndex 因为它是值类型操作而不是引用类型操作。但我没有任何支持。